回答編集履歴
4
typo 修正
answer
CHANGED
@@ -6,9 +6,7 @@
|
|
6
6
|
|
7
7
|
```javascript
|
8
8
|
class Node {
|
9
|
-
|
9
|
+
|
10
|
-
return node instanceof Node;
|
11
|
-
}
|
12
10
|
constructor ( id ) {
|
13
11
|
this.parent = null
|
14
12
|
this.id = id;
|
@@ -19,7 +17,7 @@
|
|
19
17
|
}
|
20
18
|
appendChild( node ) {
|
21
19
|
if( Node.isNode(node) ) {
|
22
|
-
node.parent = this;
|
20
|
+
node.parent = this; // parent
|
23
21
|
this.children.push( node );
|
24
22
|
}
|
25
23
|
}
|
@@ -28,7 +26,7 @@
|
|
28
26
|
let idx = this.children.indexOf( node );
|
29
27
|
if( ~idx ) {
|
30
28
|
this.children.splice( idx, 1 );
|
31
|
-
node.parent = null;
|
29
|
+
node.parent = null; // parent
|
32
30
|
}
|
33
31
|
}
|
34
32
|
}
|
@@ -40,9 +38,6 @@
|
|
40
38
|
}
|
41
39
|
return rslt;
|
42
40
|
}
|
43
|
-
append( ...nodes ) {
|
44
|
-
nodes.forEach( this.appendChild )
|
45
|
-
}
|
46
41
|
|
47
42
|
toJson () {
|
48
43
|
let
|
@@ -56,6 +51,10 @@
|
|
56
51
|
return { id, children };
|
57
52
|
}
|
58
53
|
|
54
|
+
static isNode( node ) {
|
55
|
+
return node instanceof Node;
|
56
|
+
}
|
57
|
+
|
59
58
|
static fromDatas ( datas ) {
|
60
59
|
let rootNode;
|
61
60
|
for ( let {id, parent} of datas ) {
|
@@ -87,7 +86,7 @@
|
|
87
86
|
];
|
88
87
|
var tree1 = Node.fromDatas(datas).toJson();
|
89
88
|
|
90
|
-
console.log(
|
89
|
+
console.log( tree1 ); // { id, parent, children } : ルートノード
|
91
90
|
|
92
91
|
/*
|
93
92
|
0①--1②--3③--5④
|
3
typo 修正
answer
CHANGED
File without changes
|
2
追記
answer
CHANGED
@@ -120,4 +120,9 @@
|
|
120
120
|
console.log( tree[0].children[1] );
|
121
121
|
|
122
122
|
console.log( JSON.stringify( tree, null, 2) )
|
123
|
-
```
|
123
|
+
```
|
124
|
+
----
|
125
|
+
追記)
|
126
|
+
|
127
|
+
DOM ライクな実装は「ルートが1つ」に制限されますが、「文書断片を意味するノードをルートとする」ことを考えれば、その断片がもつ children を tree の Collection とするアイディアになります。
|
128
|
+
(上記回答では未実装です)
|
1
訂正
answer
CHANGED
@@ -111,7 +111,7 @@
|
|
111
111
|
var tree2 = Node.fromDatas(datas2);
|
112
112
|
console.log( tree2 ); // { id, parent, children } : ルートノード
|
113
113
|
|
114
|
-
var tree = [ tree2 ]; // 探索用に collection ライクにする。
|
114
|
+
var tree = [ tree2.toJson() ]; // 探索用に collection ライクにする。
|
115
115
|
console.log( tree );
|
116
116
|
console.log( tree[0].children );
|
117
117
|
console.log( tree[0].children[0].children );
|
@@ -119,5 +119,5 @@
|
|
119
119
|
console.log( tree[0].children[0].children[1].children );
|
120
120
|
console.log( tree[0].children[1] );
|
121
121
|
|
122
|
-
console.log( JSON.stringify(
|
122
|
+
console.log( JSON.stringify( tree, null, 2) )
|
123
123
|
```
|