Skip to content

Commit

Permalink
feat: 馃幐 added getFlattenedTreePaths selector
Browse files Browse the repository at this point in the history
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
  • Loading branch information
diogofcunha committed Jan 27, 2019
1 parent ec1c68a commit ea17dae
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,35 @@ Array [
},
]
`;

exports[`getFlattenedTreePaths, should match snapshot 1`] = `
Array [
Array [
0,
],
Array [
0,
2,
],
Array [
0,
2,
3,
],
Array [
0,
2,
4,
],
Array [
0,
5,
],
Array [
1,
],
Array [
"z",
],
]
`;
6 changes: 5 additions & 1 deletion src/selectors/__tests__/getFlattenedTree.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import {getFlattenedTree} from '../getFlattenedTree';
import {getFlattenedTree, getFlattenedTreePaths} from '../getFlattenedTree';
import {Nodes} from '../../../testData/sampleTree';

describe('getFlattenedTree', () => {
it('should match snapshot', () => {
expect(getFlattenedTree(Nodes)).toMatchSnapshot();
});
});

test('getFlattenedTreePaths, should match snapshot', () => {
expect(getFlattenedTreePaths(Nodes)).toMatchSnapshot();
});
17 changes: 17 additions & 0 deletions src/selectors/getFlattenedTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,20 @@ export const getFlattenedTree = (nodes, parents = []) =>

return [...flattenedTree, nodeWithHelpers, ...getFlattenedTree(node.children, [...parents, node.id])];
}, []);

export const getFlattenedTreePaths = (nodes, parents = []) => {
const paths = [];

for (const node of nodes) {
const {id} = node;

if (!nodeHasChildren(node) || !isNodeExpanded(node)) {
paths.push(parents.concat(id));
} else {
paths.push(parents.concat(id));
paths.push(...getFlattenedTreePaths(node.children, [...parents, id]));
}
}

return paths;
};

0 comments on commit ea17dae

Please sign in to comment.