-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (51 loc) · 1.55 KB
/
index.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
59
/**
* Function to recursively update a given node and its children inside a tree structure
* Works for frozen objects
* To run tests use `npm test` or `yarn test`.
*
* @param {object} tree - Tree to update
* @param {string} id - Node id
* @param {object} values - Data to update from
* @param {boolean} isTreeCopyCreated - Flag to prevent rewriting tree copy
*
* @return {object} Unfrozen tree copy with updated data
*/
function updateTree(tree, id, values, isTreeCopyCreated = false) {
let unfrozenTreeCopy = isTreeCopyCreated ? tree : {};
if (!isTreeCopyCreated) {
Object.keys(tree).forEach(key => {
const frozenTreeNode = tree[key];
const nodeCopy = {};
Object.defineProperties(nodeCopy, {
id: {
value: frozenTreeNode.id,
writable: true,
enumerable: true,
configurable: true,
},
value: {
value: frozenTreeNode.value,
writable: true,
enumerable: true,
configurable: true,
},
children: {
value: frozenTreeNode.children,
writable: true,
enumerable: true,
configurable: true,
},
});
unfrozenTreeCopy[frozenTreeNode.id] = nodeCopy;
});
}
const unfrozenNode = unfrozenTreeCopy[id];
unfrozenNode.value = values.value;
if (unfrozenTreeCopy[id].children.length) {
unfrozenTreeCopy[id].children.forEach(childId => {
updateTree(unfrozenTreeCopy, childId, values, true);
});
}
return unfrozenTreeCopy;
}
module.exports = updateTree;