-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathD3_test_code.js
More file actions
130 lines (108 loc) · 2.55 KB
/
D3_test_code.js
File metadata and controls
130 lines (108 loc) · 2.55 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class Node {
constructor(data) {
this.data = data;
this.depth = this.height = 0;
this.parent = null;
}
each(callback, that) {
let index = -1;
for (const node of this) {
callback.call(that, node, ++index, this);
}
return this;
}
eachBefore(callback, that) {
let node = this;
let nodes = [node];
let children;
let index = -1;
while ((node = nodes.pop())) {
callback.call(that, node, ++index, this);
if ((children = node.children)) {
for (let i = children.length - 1; i >= 0; --i) {
nodes.push(children[i]);
}
}
}
return this;
}
descendants() {
return Array.from(this);
}
}
function* iterator() {
let node = this;
let current;
let next = [node];
let children;
do {
(current = next), (next = []);
while ((node = current.pop())) {
yield node;
if ((children = node.children)) {
for (let i = 0; i < children.length; ++i) {
next.unshift(children[i]);
}
}
}
} while (next.length);
}
function hierarchy(data, children) {
if (children === undefined) {
children = objectChildren;
}
let root = new Node(data);
let node;
let nodes = [root];
let child;
let childs;
let n;
while ((node = nodes.pop())) {
if (
(childs = children(node.data)) &&
(n = (childs = Array.from(childs)).length)
) {
node.children = childs;
for (let i = n - 1; i >= 0; --i) {
nodes.push((child = childs[i] = new Node(childs[i])));
child.parent = node;
child.depth = node.depth + 1;
}
}
}
return root.eachBefore(computeHeight);
}
function objectChildren(d) {
return d.children;
}
function computeHeight(node) {
let height = 0;
do node.height = height;
while ((node = node.parent) && node.height < ++height);
}
// hierarchy.prototype = {
// constructor: Node.constructor,
// [Symbol.iterator]: iterator,
// }
Node.prototype = hierarchy.prototype ={
[Symbol.iterator]: iterator,
};
function main() {
let data = {
name: "root",
children: [
{ name: "A", children: [{ name: "C" }, { name: "D" }, { name: "E" }] },
{ name: "B", children: [{ name: "F" }, { name: "G" }, { name: "H" }] },
{ name: "I", children: [{ name: "J" }, { name: "K" }, { name: "L" }] }
],
};
let root = hierarchy(data);
let desc = root.descendants();
console.log("desc =", desc);
root
.descendants()
.forEach((node, i) =>
console.log(`Node.name = ${node.data.name}, Node iterator index = ${i}`)
);
}
main();