forked from TreeJS/TreeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.js
More file actions
70 lines (70 loc) · 1.9 KB
/
Copy pathtree.js
File metadata and controls
70 lines (70 loc) · 1.9 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function(){
var Tree = function(value){
this._parent = null;
this._children = [];
this.value = value;
};
Tree.prototype.setParent = function(parent){
this._parent = parent;
this._parent._children.push(this);
};
Tree.prototype.addChild = function(tree){
this._children.push(tree);
tree._parent = this;
};
Tree.prototype.getRoot = function(){
var currentNode = this;
while(currentNode._parent !== null){
currentNode = currentNode._parent;
}
return currentNode;
};
Tree.prototype.hasChild = function(node, validator){
for (var i = 0; i < this._children.length; i++) {
if(validator(node, this._children[i])){
return true;
}
}
return false;
};
Tree.prototype.findNode = function(tree, validator){
validator = validator || function(a,b){return a.value === b.value;};
if(validator(tree, this)){
return this;
}
for (var i = 0; i < this._children.length; i++) {
var foundNode = this._children[i].findNode(tree, validator);
if(foundNode){
return foundNode;
}
}
return undefined;
};
Tree.prototype.removeDescendant = function(tree, validator){
validator = validator || function(a,b){return a.value === b.value;};
var foundNode = this.findNode(tree, validator);
if(!foundNode){
return false;
}
var parent = foundNode._parent;
parent._children = _.reject(parent._children, function(vizNode){
return validator(vizNode, tree);
});
return tree;
};
Tree.prototype.contains = function(node, validator){
validator = validator || function(a,b){return a.value === b.value;};
if(validator(this, node)){
return true;
}
var result = false;
for (var i = 0; i < this._children.length; i++) {
result = this._children[i].contains(node);
if(result){
break;
}
}
return result;
};
return Tree;
}();