Skip to content

Commit ea17dae

Browse files
committed
feat: 🎸 added getFlattenedTreePaths selector
added a selector that crawls a tree, flattens it for visible nodes and creates an array with the path to reach the node on the original tree
1 parent ec1c68a commit ea17dae

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

src/selectors/__tests__/__snapshots__/getFlattenedTree.test.js.snap

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,3 +140,35 @@ Array [
140140
},
141141
]
142142
`;
143+
144+
exports[`getFlattenedTreePaths, should match snapshot 1`] = `
145+
Array [
146+
Array [
147+
0,
148+
],
149+
Array [
150+
0,
151+
2,
152+
],
153+
Array [
154+
0,
155+
2,
156+
3,
157+
],
158+
Array [
159+
0,
160+
2,
161+
4,
162+
],
163+
Array [
164+
0,
165+
5,
166+
],
167+
Array [
168+
1,
169+
],
170+
Array [
171+
"z",
172+
],
173+
]
174+
`;
Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
import {getFlattenedTree} from '../getFlattenedTree';
1+
import {getFlattenedTree, getFlattenedTreePaths} from '../getFlattenedTree';
22
import {Nodes} from '../../../testData/sampleTree';
33

44
describe('getFlattenedTree', () => {
55
it('should match snapshot', () => {
66
expect(getFlattenedTree(Nodes)).toMatchSnapshot();
77
});
88
});
9+
10+
test('getFlattenedTreePaths, should match snapshot', () => {
11+
expect(getFlattenedTreePaths(Nodes)).toMatchSnapshot();
12+
});

src/selectors/getFlattenedTree.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,20 @@ export const getFlattenedTree = (nodes, parents = []) =>
1212

1313
return [...flattenedTree, nodeWithHelpers, ...getFlattenedTree(node.children, [...parents, node.id])];
1414
}, []);
15+
16+
export const getFlattenedTreePaths = (nodes, parents = []) => {
17+
const paths = [];
18+
19+
for (const node of nodes) {
20+
const {id} = node;
21+
22+
if (!nodeHasChildren(node) || !isNodeExpanded(node)) {
23+
paths.push(parents.concat(id));
24+
} else {
25+
paths.push(parents.concat(id));
26+
paths.push(...getFlattenedTreePaths(node.children, [...parents, id]));
27+
}
28+
}
29+
30+
return paths;
31+
};

0 commit comments

Comments
 (0)