Node:drawTree(): creates a String representing the node in the tree

The NodeItem implementation on includes nodes with names, or where they
have child nodes. In which case the are shown as '(unnamed)'.
This commit is contained in:
Paul Campbell 2016-05-24 11:25:59 +01:00
parent b278fc0f98
commit b2c3032ec0
2 changed files with 25 additions and 0 deletions

View file

@ -146,6 +146,16 @@ public interface Node<T> {
*/
Node<T> 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

View file

@ -305,6 +305,21 @@ public class NodeItem<T> implements Node<T> {
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;