Skip to content

Instantly share code, notes, and snippets.

@thethomaseffect
Last active January 2, 2016 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thethomaseffect/8344338 to your computer and use it in GitHub Desktop.
Save thethomaseffect/8344338 to your computer and use it in GitHub Desktop.
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