-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathgetFlattenedTree.js
44 lines (36 loc) · 1.39 KB
/
getFlattenedTree.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
export const isNodeExpanded = node => node.state && node.state.expanded;
export const nodeHasChildren = node => node.children && node.children.length;
export const getFlattenedTree = (nodes, parents = []) => {
const flattenedTree = [];
const stack = [...nodes.map(node => ({node, parents}))];
while (stack.length > 0) {
const {node, parents} = stack.shift();
const deepness = parents.length;
const nodeWithHelpers = {...node, deepness, parents};
if (!nodeHasChildren(node) || !isNodeExpanded(node)) {
flattenedTree.push(nodeWithHelpers);
} else {
flattenedTree.push(nodeWithHelpers);
stack.unshift(...node.children.map(child => ({node: child, parents: [...parents, node.id]})));
}
}
return flattenedTree;
};
export const getFlattenedTreePaths = (nodes, parents = []) => {
const paths = [];
const stack = [...nodes.map(node => ({node, parents}))];
while (stack.length > 0) {
const {node, parents} = stack.shift();
const {id} = node;
if (!nodeHasChildren(node) || !isNodeExpanded(node)) {
paths.push([...parents, id]);
} else {
paths.push([...parents, id]);
stack.unshift(...node.children.map(child => ({node: child, parents: [...parents, id]})));
}
}
return paths;
};
export const doesChangeAffectFlattenedTree = (previousNode, nextNode) => {
return isNodeExpanded(previousNode) !== isNodeExpanded(nextNode);
};