Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple tree implementation in TypeScript using only a single one-line function. It's obviously seriously basic and insert/delete operations would not be very efficient but then again your data is immutable so who needs to do that right? ;)
function N(...nodes:any[]) {
return nodes;
}
var tree =
N("root",
N("one", "one",
N("two", "two")),
N("one", "one",
N("two")));
// Get a Node by index
tree[1][1] // -> "one"
// If a node has children they are at index + 1
tree[1][2] // -> ["two", "two"]
// To get the parent of a node, knock off an index and -1 it
tree[0] // -> "root"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment