Skip to content

Commit a494dfe

Browse files
author
Philipp Alferov
committed
Refactoring
1 parent 93df452 commit a494dfe

File tree

1 file changed

+33
-26
lines changed

1 file changed

+33
-26
lines changed

index.js

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,45 @@
11
'use strict';
22
var util = require('util');
33

4-
function createTree(list, rootNodes, customID) {
4+
var exists = function(obj, key) {
5+
return obj != null && Object.hasOwnProperty.call(obj, key);
6+
};
7+
8+
var createTree = function(array, rootNodes, customID) {
59
var tree = [];
610

7-
for (var prop in rootNodes) {
8-
if (!rootNodes.hasOwnProperty(prop)) {
9-
continue;
11+
for (var key in rootNodes) {
12+
if (!exists(rootNodes, key)) {
13+
continue ;
1014
}
15+
var parentNode = rootNodes[key];
16+
var childNode = array[parentNode[customID]];
1117

12-
var node = rootNodes[prop];
13-
var listItem = list[node[customID]];
14-
15-
if (listItem) {
16-
node.children = createTree(list, listItem, customID);
18+
if (childNode) {
19+
parentNode.children = createTree(array, childNode, customID);
1720
}
1821

19-
tree.push(node);
22+
tree.push(parentNode);
2023
}
2124

2225
return tree;
23-
}
26+
};
2427

25-
function orderByParents(list, config) {
28+
var groupByParents = function(array, options) {
2629
var parents = {};
27-
var parentProperty = config.parentProperty;
30+
var parentProperty = options.parentProperty;
2831

29-
list.forEach(function(item) {
30-
var parentID = item[parentProperty] || 0;
31-
parents[parentID] = parents[parentID] || [];
32-
parents[parentID].push(item);
32+
array.forEach(function(item) {
33+
var parentID = item[parentProperty] || options.rootID;
34+
if (exists(parents, parentID)) {
35+
parents[parentID].push(item);
36+
} else {
37+
parents[parentID] = [item];
38+
}
3339
});
3440

3541
return parents;
36-
}
42+
};
3743

3844
/**
3945
* arrayToTree
@@ -52,19 +58,20 @@ function orderByParents(list, config) {
5258
*/
5359

5460
module.exports = function arrayToTree(options) {
55-
var config = util._extend({
56-
parentProperty: 'parent_id',
57-
data: [],
58-
customID: 'id'
59-
}, options);
61+
options = util._extend({
62+
parentProperty: 'parent_id',
63+
data: [],
64+
customID: 'id',
65+
rootID: '0'
66+
}, options);
6067

61-
var data = config.data;
68+
var data = options.data;
6269

6370
if (!util.isArray(data)) {
6471
throw new Error('Expected an object but got an invalid argument');
6572
}
6673

6774
var cloned = data.slice();
68-
var ordered = orderByParents(cloned, config);
69-
return createTree(ordered, ordered[0], config.customID);
75+
var grouped = groupByParents(cloned, options);
76+
return createTree(grouped, grouped[options.rootID], options.customID);
7077
};

0 commit comments

Comments
 (0)