-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path4-newfunc.js
More file actions
78 lines (57 loc) · 1.52 KB
/
4-newfunc.js
File metadata and controls
78 lines (57 loc) · 1.52 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
71
72
73
74
75
76
77
78
'use strict';
function Node(parent, name, data) {
this.name = name;
this.data = data;
if (parent) {
this.parent = parent;
parent[name] = this;
}
this.child = [];
}
function Tree(name, data) {
this.root = new Node(null, name, data);
}
Tree.prototype.visitDepth = function(callback) {
(function recursive(currNode) {
const len = currNode.child.length;
let num;
for (num = 0; num < len; ++num) {
recursive(currNode.child[num]);
}
callback(currNode);
})(this.root);
};
Tree.prototype.isHave = function(callback) {
this.visitDepth.call(this, callback);
};
Tree.prototype.addData = function(name, data, whereAdd) {
let parent = null;
const callback = function(n) {
if (n.name === whereAdd) {
parent = n;
}
};
this.isHave(callback);
const node = new Node(parent, name, data);
if (parent) {
parent.child.push(node);
node.parent = parent;
} else {
throw new Error('Parent not exist!');
}
};
const tree = new Tree('one', 1);
tree.root.child.push(new Node(tree, 'two', 2));
tree.root.child.push(new Node(tree, 'three', 3));
tree.root.child.push(new Node(tree, 'four', 4));
tree.root.child[0].child.push(new Node(tree.root.child[0], 'five', 5));
tree.root.child[0].child.push(new Node(tree.root.child[0], 'six', 6));
tree.root.child[2].child.push(new Node(tree.root.child[2], 'seven', 7));
tree.isHave(n => {
if (n.name === 'five') {
console.dir(n);
}
});
tree.visitDepth(n => console.dir(n));
tree.addData('qwe', 456, 'two');
console.dir(tree);