-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.js
39 lines (35 loc) · 804 Bytes
/
tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var Tree = function(value){
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function(child){
if (!child || !(child instanceof Tree)){
child = new Tree(child);
}
if(!this.isDescendant(child)){
this.children.push(child);
}else {
throw new Error("Already child");
}
return child;
};
Tree.prototype.isDescendant = function(child){
if(this.children.indexOf(child) !== -1){
return true;
}else{
for(var i = 0; i < this.children.length; i++){
if(this.children[i].isDescendant(child)){
return true;
}
}
return false;
}
};
Tree.prototype.removeChild = function(child){
var index = this.children.indexOf(child);
if(index !== -1){
this.children.splice(index,1);
}else{
throw new Error("Not a child");
}
};