Skip to content

Commit 4fc5f0d

Browse files
author
Philipp Alferov
committed
Merge branch 'taoqf-master'
2 parents da95f6e + 6e33e1a commit 4fc5f0d

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

index.d.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export = arrayToTree;
2+
3+
declare function arrayToTree<T>(data: T[], options?: Partial<arrayToTree.Options>): Array<arrayToTree.Tree<T>>;
4+
5+
declare namespace arrayToTree {
6+
interface Options {
7+
childrenProperty: string;
8+
parentProperty: string;
9+
customID: string;
10+
rootID: string;
11+
}
12+
13+
type Tree<T> = T & {
14+
children?: Array<Tree<T>>;
15+
};
16+
}

index.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,23 @@ var groupByParents = function(array, options) {
4747
}, {});
4848
};
4949

50+
function isObject(o) {
51+
return Object.prototype.toString.call(o) === '[object Object]';
52+
}
53+
54+
function deepClone(data) {
55+
if (Array.isArray(data)) {
56+
return data.map(deepClone);
57+
} else if (isObject(data)) {
58+
return Object.keys(data).reduce(function(o, k) {
59+
o[k] = deepClone(data[k]);
60+
return o;
61+
}, {});
62+
} else {
63+
return data;
64+
}
65+
}
66+
5067
/**
5168
* arrayToTree
5269
* Convert a plain array of nodes (with pointers to parent nodes) to a nested
@@ -82,7 +99,7 @@ module.exports = function arrayToTree(data, options) {
8299
throw new TypeError('Expected an object but got an invalid argument');
83100
}
84101

85-
var grouped = groupByParents(data.slice(), options);
102+
var grouped = groupByParents(deepClone(data), options);
86103
return createTree(
87104
grouped,
88105
grouped[options.rootID],

0 commit comments

Comments
 (0)