Skip to content

Instantly share code, notes, and snippets.

@OfTheDelmer
Created December 1, 2013 00:24
Show Gist options
  • Save OfTheDelmer/7726951 to your computer and use it in GitHub Desktop.
Save OfTheDelmer/7726951 to your computer and use it in GitHub Desktop.
var Node = function(data, parent){
this.children = null;
if(data === undefined){
data = null;
}
parent !== undefined?parent.addChild(data):this.data = data;
};
Node.prototype.addChild = function(child){
var newNode;
newNode = new Node(child);
this.lastChild = newNode;
if(this.children === null){
this.children = [newNode];
} else{
this.children.push(newNode);
}
var _this = this;
newNode.parent = function(){
return _this;
};
return newNode;
};
Node.prototype.addChildren = function(items){
if(items.constructor === Array){
var _this = this;
var addItem = function(item){
_this.addChild(item);
};
items.forEach(addItem);
return _this;
}
};
var Tree = function(){
this.rootNode = null;
};
Tree.prototype.mapToChildren = function(parent, items, action){
if(items.constructor === Array){
action === undefined? parent.addChildren(items): parent.addChildren(items.map(action));
}
};
Tree.prototype.insert = function(data, parent) {
var newNode;
if (this.rootNode === null) {
newNode = new Node(data);
this.rootNode = newNode;
} else if (parent !== undefined) {
newNode = new Node(data, parent);
} else {
newNode = this.lastNode.addChild(data);
}
this.lastNode = newNode;
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment