diff --git a/src/main/java/net/kemitix/node/Node.java b/src/main/java/net/kemitix/node/Node.java index 04bec0e..e2f074f 100644 --- a/src/main/java/net/kemitix/node/Node.java +++ b/src/main/java/net/kemitix/node/Node.java @@ -125,6 +125,16 @@ public interface Node { */ Optional> findChild(T child); + /** + * Fetches the node for the child if present. + * + * @param child the child's data to search for + * + * @return the child node if found + * + * @throws NodeException if the node is not found + */ + Node getChild(T child); /** * Checks if the node is an ancestor. diff --git a/src/main/java/net/kemitix/node/NodeItem.java b/src/main/java/net/kemitix/node/NodeItem.java index c9d70f8..acd883d 100644 --- a/src/main/java/net/kemitix/node/NodeItem.java +++ b/src/main/java/net/kemitix/node/NodeItem.java @@ -246,6 +246,14 @@ public class NodeItem implements Node { .findAny(); } + @Override + public Node getChild(final T child) { + Optional> optional = findChild(child); + if (optional.isPresent()) + return optional.get(); + throw new NodeException("Child not found"); + } + /** * Checks if the node is an ancestor. * diff --git a/src/test/java/net/kemitix/node/NodeItemTest.java b/src/test/java/net/kemitix/node/NodeItemTest.java index 53b0c07..251d690 100644 --- a/src/test/java/net/kemitix/node/NodeItemTest.java +++ b/src/test/java/net/kemitix/node/NodeItemTest.java @@ -901,4 +901,25 @@ public class NodeItemTest { assertThat(child.getParent()).isSameAs(node); assertThat(node.getChildren()).containsExactly(child); } + + @Test + public void canGetChildWhenFound() { + //given + node = new NodeItem<>("data"); + Node child = new NodeItem<>("child data", "child name", node); + //when + Node found = node.getChild("child data"); + //then + assertThat(found).isSameAs(child); + } + + @Test + public void canGetChildWhenNotFound() { + //given + exception.expect(NodeException.class); + exception.expectMessage("Child not found"); + node = new NodeItem<>("data"); + //when + node.getChild("child data"); + } }