Skip to content

Commit 66b645c

Browse files
author
Philipp Alferov
committed
Refactoring
1 parent 4482b1c commit 66b645c

File tree

2 files changed

+16
-14
lines changed

2 files changed

+16
-14
lines changed

index.js

+14-12
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
'use strict';
22
var isArray = require('isarray');
3-
var extend = require('shallow-object-extend');
4-
var exists = require('property-exists');
3+
var extend = require('extend');
4+
var exists = require('property-exists');
55

66
var createTree = function(array, rootNodes, customID) {
77
var tree = [];
88

99
for (var rootNode in rootNodes) {
10-
if (!exists(rootNodes, rootNode)) {
11-
continue ;
12-
}
1310
var node = rootNodes[rootNode];
1411
var childNode = array[node[customID]];
1512

13+
if (!node && !exists(rootNodes, rootNode)) {
14+
continue ;
15+
}
16+
1617
if (childNode) {
1718
node.children = createTree(array, childNode, customID);
1819
}
@@ -25,15 +26,16 @@ var createTree = function(array, rootNodes, customID) {
2526

2627
var groupByParents = function(array, options) {
2728
var parents = {};
28-
var parentProperty = options.parentProperty;
2929

3030
array.forEach(function(item) {
31-
var parentID = item[parentProperty] || options.rootID;
32-
if (exists(parents, parentID)) {
31+
var parentID = item[options.parentProperty] || options.rootID;
32+
33+
if (parentID && exists(parents, parentID)) {
3334
parents[parentID].push(item);
34-
} else {
35-
parents[parentID] = [item];
35+
return ;
3636
}
37+
38+
parents[parentID] = [item];
3739
});
3840

3941
return parents;
@@ -63,10 +65,10 @@ module.exports = function arrayToTree(data, options) {
6365
parentProperty: 'parent_id',
6466
customID: 'id',
6567
rootID: '0'
66-
}, options || {});
68+
}, options);
6769

6870
if (!isArray(data)) {
69-
throw new Error('Expected an object but got an invalid argument');
71+
throw new TypeError('Expected an object but got an invalid argument');
7072
}
7173

7274
var cloned = data.slice();

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@
3232
},
3333
"license": "MIT",
3434
"dependencies": {
35+
"extend": "^3.0.0",
3536
"isarray": "0.0.1",
36-
"property-exists": "^1.0.1",
37-
"shallow-object-extend": "0.0.1"
37+
"property-exists": "^1.0.1"
3838
}
3939
}

0 commit comments

Comments
 (0)