forked from joaonuno/flat-to-nested-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (76 loc) · 2.32 KB
/
index.js
File metadata and controls
83 lines (76 loc) · 2.32 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
module.exports = (function () {
'use strict';
/**
* Create a new FlatToNested object.
*
* @constructor
* @param {object} config The configuration object.
*/
function FlatToNested(config) {
this.config = config = config || {};
this.config.id = config.id || 'id';
this.config.parent = config.parent || 'parent';
this.config.children = config.children || 'children';
}
/**
* Convert a hierarchy from flat to nested representation.
*
* @param {array} flat The array with the hierachy flat representation.
*/
FlatToNested.prototype.convert = function (flat) {
var i, len, temp, roots, id, parent, nested, pendingChildOf, flatEl;
i = 0;
roots = [];
temp = {};
pendingChildOf = {};
for (i, len = flat.length; i < len; i++) {
flatEl = flat[i];
id = flatEl[this.config.id];
parent = flatEl[this.config.parent];
temp[id] = flatEl;
if (parent === undefined || parent === null) {
// Current object has no parent, so it's a root element.
roots.push(flatEl);
} else {
if (temp[parent] !== undefined) {
// Parent is already in temp, adding the current object to its children array.
initPush(this.config.children, temp[parent], flatEl);
} else {
// Parent for this object is not yet in temp, adding it to pendingChildOf.
initPush(parent, pendingChildOf, flatEl);
}
delete flatEl[this.config.parent];
}
if (pendingChildOf[id] !== undefined) {
// Current object has children pending for it. Adding these to the object.
multiInitPush(this.config.children, flatEl, pendingChildOf[id]);
}
}
if (roots.length === 1) {
nested = roots[0];
} else if (roots.length > 1) {
nested = {};
nested[this.config.children] = roots;
} else {
nested = {};
}
return nested;
};
function initPush(arrayName, obj, toPush) {
if (obj[arrayName] === undefined) {
obj[arrayName] = [];
}
obj[arrayName].push(toPush);
}
function multiInitPush(arrayName, obj, toPushArray) {
var len;
len = toPushArray.length;
if (obj[arrayName] === undefined) {
obj[arrayName] = [];
}
while (len-- > 0) {
obj[arrayName].push(toPushArray.shift());
}
}
return FlatToNested;
})();