Skip to content

Instantly share code, notes, and snippets.

@Cfeusier
Created December 14, 2014 09:13
Show Gist options
  • Save Cfeusier/e31b3050db3d4642a700 to your computer and use it in GitHub Desktop.
Save Cfeusier/e31b3050db3d4642a700 to your computer and use it in GitHub Desktop.
Simple Tree implementation in JavaScript
var Tree = function(value) {
var newTree = {};
newTree.value = value;
newTree.children = [];
_.extend(newTree, treeMethods);
return newTree;
};
var treeMethods = {};
treeMethods.addChild = function(value) {
this.children.push(Tree(value));
};
treeMethods.contains = function(target, root) {
root = root || this;
if (root.value === target) return true; // base-case
for (var i = 0; i < root.children.length; i++) {
if (this.contains(target, root.children[i])) return true;
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment