Skip to content

Commit 01e1685

Browse files
author
Philipp Alferov
committed
Implement basic library functionality
1 parent 711213a commit 01e1685

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

index.js

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,43 @@
1+
'use strict';
2+
3+
function createTree(list, rootNodes) {
4+
var tree = [];
5+
6+
for (var prop in rootNodes) {
7+
if (!rootNodes.hasOwnProperty(prop)) {
8+
continue;
9+
}
10+
11+
var node = rootNodes[prop];
12+
13+
if (list[node.id]) {
14+
node.children = createTree(list, list[node.id]);
15+
}
16+
17+
tree.push(node);
18+
}
19+
20+
return tree;
21+
}
22+
23+
function orderByParents(list) {
24+
var parents = {};
25+
26+
list.forEach(function(item) {
27+
var parentID = item.parent_id || 0;
28+
parents[parentID] = parents[parentID] || [];
29+
parents[parentID].push(item);
30+
});
31+
32+
return parents;
33+
}
34+
135
function clone(obj) {
236
return JSON.parse(JSON.stringify(obj));
337
}
438

539
module.exports = function(obj) {
640
var cloned = clone(obj);
7-
8-
return cloned;
41+
var ordered = orderByParents(cloned);
42+
return createTree(ordered, ordered[0]);
943
};

0 commit comments

Comments
 (0)