Skip to content

Instantly share code, notes, and snippets.

@bluurn
Created January 29, 2019 16:16
Show Gist options
  • Save bluurn/bff2df52b29d806d43061b16cec80a8d to your computer and use it in GitHub Desktop.
Save bluurn/bff2df52b29d806d43061b16cec80a8d to your computer and use it in GitHub Desktop.
JS: Tree Implementation
function Node(data) {
this.data = data;
this.parent = null;
this.children = [];
}
function Tree(data) {
this._root = new Node(data);
}
Tree.prototype.traverseDF = function(cb) {
(function recurse(current) {
for(var i = 0; i < current.children.length; i++) {
recurse(current.children[i]);
}
cb(current);
})(this._root)
};
Tree.prototype.traverseBF = function(cb) {
var queue = [];
queue.push(this._root);
current = queue.shift();
while(current) {
for(var i = 0; i < current.children.length; i++) {
queue.push(current.children[i]);
}
cb(current);
current = queue.shift();
}
};
Tree.prototype.contains = function(callback, traversal) {
traversal.call(this, callback);
};
Tree.prototype.add = function(data, toData, traversal) {
var child = new Node(data),
parent = null,
callback = function(node) {
if (node.data === toData) {
parent = node;
}
};
this.contains(callback, traversal);
if (parent) {
parent.children.push(child);
child.parent = parent;
} else {
throw new Error('Cannot add node to a non-existent parent.');
}
};
Tree.prototype.remove = function(data, fromData, traversal) {
var tree = this,
parent = null,
childToRemove = null,
index;
var callback = function(node) {
if (node.data === fromData) {
parent = node;
}
};
this.contains(callback, traversal);
if (parent) {
index = parent.children.indexOf(data);
if (index === undefined) {
throw new Error('Node to remove does not exist.');
} else {
childToRemove = parent.children.splice(index, 1);
}
} else {
throw new Error('Parent does not exist.');
}
return childToRemove;
};
var tree = new Tree('one');
tree._root.children.push(new Node('two'));
tree._root.children[0].parent = tree;
tree._root.children.push(new Node('three'));
tree._root.children[1].parent = tree;
tree._root.children.push(new Node('four'));
tree._root.children[2].parent = tree;
tree._root.children[0].children.push(new Node('five'));
tree._root.children[0].children[0].parent = tree._root.children[0];
tree._root.children[0].children.push(new Node('six'));
tree._root.children[0].children[1].parent = tree._root.children[0];
tree._root.children[2].children.push(new Node('seven'));
tree._root.children[2].children[0].parent = tree._root.children[2];
/*
creates this tree
one
├── two
│ ├── five
│ └── six
├── three
└── four
└── seven
*/
// tree.traverseDF(it => console.log(it.data));
// tree.traverseBF(it => console.log(it.data));
// console.dir(tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment