-
Notifications
You must be signed in to change notification settings - Fork 30
/
list-to-tree.js
58 lines (48 loc) · 1.21 KB
/
list-to-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const IronTree = require('@denq/iron-tree');
const defaultOptions = {
key_id: 'id' ,
key_parent: 'parent' ,
key_child: 'child',
empty_children: false,
};
function sortBy(collection, propertyA, propertyB) {
return collection.sort(function(a, b) {
if (a[propertyB] < b[propertyB]) {
if (a[propertyA] > b[propertyA]) {
return 1;
}
return -1;
} else {
if (a[propertyA] < b[propertyA]) {
return -1;
}
return 1;
}
});
};
module.exports = class LTT{
constructor(list, options = {}) {
const _list = list.map((item) => item);
options = Object.assign({}, defaultOptions, options);
this.options = options;
const { key_id, key_parent } = options;
sortBy(_list, key_parent, key_id);
const tree = new IronTree({ [key_id]: 0 });
_list.forEach((item, index) => {
tree.add((parentNode) => {
return parentNode.get(key_id) === item[key_parent];
}, item);
});
this.tree = tree;
}
sort(criteria) {
this.tree.sort(criteria);
}
GetTree() {
const { key_child, empty_children } = this.options;
return this.tree.toJson({
key_children: key_child,
empty_children: false,
})[key_child];
}
}