Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created February 16, 2015 21:22
Show Gist options
  • Save bdkosher/557fd6e1d8d4b65da4bc to your computer and use it in GitHub Desktop.
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.
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