From b2c3032ec06ccd0df5d7062c2583bd8ddb4e2291 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Tue, 24 May 2016 11:25:59 +0100 Subject: [PATCH] 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)'. --- src/main/java/net/kemitix/node/Node.java | 10 ++++++++++ src/main/java/net/kemitix/node/NodeItem.java | 15 +++++++++++++++ 2 files changed, 25 insertions(+) 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;