Skip to content

Commit 1d4b522

Browse files
author
Philipp Alferov
committed
Refactoring
1 parent 67f97fa commit 1d4b522

File tree

2 files changed

+9
-13
lines changed

2 files changed

+9
-13
lines changed

index.js

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,20 +24,17 @@ var createTree = function(array, rootNodes, customID) {
2424
};
2525

2626
var groupByParents = function(array, options) {
27-
var parents = {};
28-
29-
array.forEach(function(item) {
27+
return array.reduce(function(prev, item) {
3028
var parentID = item[options.parentProperty] || options.rootID;
3129

32-
if (parentID && parents.hasOwnProperty(parentID)) {
33-
parents[parentID].push(item);
34-
return ;
30+
if (parentID && prev.hasOwnProperty(parentID)) {
31+
prev[parentID].push(item);
32+
return prev;
3533
}
3634

37-
parents[parentID] = [item];
38-
});
39-
40-
return parents;
35+
prev[parentID] = [item];
36+
return prev;
37+
}, {});
4138
};
4239

4340
/**
@@ -59,7 +56,6 @@ var groupByParents = function(array, options) {
5956
*/
6057

6158
module.exports = function arrayToTree(data, options) {
62-
data = data || [];
6359
options = assign({
6460
parentProperty: 'parent_id',
6561
customID: 'id',

test/test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ describe('array-to-tree', function() {
5656
.to.throw(/invalid argument/);
5757
});
5858

59-
it('should return the same array if there is no pointer to parent', function() {
59+
it('returns the same array if there is no pointer to parent', function() {
6060

6161
var modified = initial.map(function(item) {
6262
delete item.parent_id;
@@ -66,7 +66,7 @@ describe('array-to-tree', function() {
6666
expect(toTree(modified))
6767
.to.be.deep.equal(modified);
6868
});
69-
})
69+
});
7070

7171
describe('with different options', function() {
7272
it('should work with custom parents links', function() {

0 commit comments

Comments
 (0)