diff --git a/src/main/java/net/kemitix/node/Node.java b/src/main/java/net/kemitix/node/Node.java index c569773..0a96c66 100644 --- a/src/main/java/net/kemitix/node/Node.java +++ b/src/main/java/net/kemitix/node/Node.java @@ -146,6 +146,16 @@ public interface Node { */ Node getChildNamed(String name); + /** + * Draw a representation of the tree. + * + * @param depth current depth for recursion + * + * @return a representation of the tree + */ + String drawTree(int depth); + + /** * Returns true if the Node has a name. * * @return true if the node has a name diff --git a/src/main/java/net/kemitix/node/NodeItem.java b/src/main/java/net/kemitix/node/NodeItem.java index fb8908b..88764e4 100644 --- a/src/main/java/net/kemitix/node/NodeItem.java +++ b/src/main/java/net/kemitix/node/NodeItem.java @@ -305,6 +305,21 @@ public class NodeItem implements Node { throw new NodeException("Named child not found"); } + @Override + public String drawTree(final int depth) { + final StringBuilder sb = new StringBuilder(); + final String unnamed = "(unnamed)"; + if (isNamed()) { + sb.append(String.format("[%1$" + (depth + name.length()) + "s]\n", + name)); + } else if (!children.isEmpty()) { + sb.append(String.format("[%1$" + (depth + unnamed) + "s]\n", + unnamed)); + } + getChildren().stream().forEach(c -> sb.append(c.drawTree(depth + 1))); + return sb.toString(); + } + @Override public boolean isNamed() { return name != null && name.length() > 0;