回答編集履歴

2

コードを整理してみた

2017/07/15 07:41

投稿

Lhankor_Mhy
Lhankor_Mhy

スコア36158

test CHANGED
@@ -52,7 +52,7 @@
52
52
 
53
53
  var before_clone = before.slice();
54
54
 
55
- var children_temp = new Array(before.length);
55
+ var children_temp = new Array(before.length+1);
56
56
 
57
57
 
58
58
 
@@ -109,3 +109,59 @@
109
109
  */
110
110
 
111
111
  ```
112
+
113
+  
114
+
115
+  
116
+
117
+ ##### コードを整理してみた
118
+
119
+ 短くなった。
120
+
121
+ ```javascript
122
+
123
+ var children_temp = Array.apply( null, Array( before.length + 1 ) ).map( function(){return []} ); // Array.prototype.fill()代替
124
+
125
+
126
+
127
+ before.forEach(function ( el, _, _ ) {
128
+
129
+ children_temp[el.parent].push(el);
130
+
131
+ });
132
+
133
+
134
+
135
+ before = before.filter(function ( el, _, _ ) {
136
+
137
+ if ( children_temp[el.id].length ) el.children = children_temp[el.id];
138
+
139
+ return ( el.parent === 0 );
140
+
141
+ });
142
+
143
+ ```
144
+
145
+
146
+
147
+ 空の配列をchildrenに許容してくれるなら、ワンライナーいける。
148
+
149
+ ```javascript
150
+
151
+ before = before.filter(
152
+
153
+ function ( el, _, _ ) {
154
+
155
+ this[el.parent].push(el);
156
+
157
+ el.children = this[el.id];
158
+
159
+ return ( el.parent === 0 );
160
+
161
+ },
162
+
163
+ Array.apply( null, Array( before.length + 1 ) ).map( function(){return []} )
164
+
165
+ );
166
+
167
+ ```

1

整形

2017/07/15 07:41

投稿

Lhankor_Mhy
Lhankor_Mhy

スコア36158

test CHANGED
@@ -64,9 +64,7 @@
64
64
 
65
65
  var target = children_temp[el.parent];
66
66
 
67
- if (target === undefined) children_temp[el.parent] = target = [
67
+ if (target === undefined) children_temp[el.parent] = target = [];
68
-
69
- ];
70
68
 
71
69
  target.push(el);
72
70