Created
February 16, 2015 21:22
-
-
Save bdkosher/557fd6e1d8d4b65da4bc to your computer and use it in GitHub Desktop.
Convert a List of Nodes to a single Node where the subsequent nodes in the List are the children of the predecessor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
String name | |
Node child | |
static Node asHierarchy(List<Node> nodes) { | |
nodes.reverse().inject(null) { prev, curr -> | |
curr.child = prev | |
curr | |
} | |
} | |
} | |
def nodes = ['A','B','C'].collect { new Node(name: it) } | |
def (nodeA, nodeB, nodeC) = nodes | |
// convert list into hierarchy | |
def top = Node.asHierarchy(nodes) | |
assert top == nodeA | |
assert nodeA.child == nodeB | |
assert nodeB.child == nodeC | |
assert nodeC.child == null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment