Skip to content

Iterative version of getFlattenedTree for improved performance on large datasets #156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions src/selectors/getFlattenedTree.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,33 @@
export const isNodeExpanded = node => node.state && node.state.expanded;
export const nodeHasChildren = node => node.children && node.children.length;

export const getFlattenedTree = (nodes, parents = []) =>
nodes.reduce((flattenedTree, node) => {
export const getFlattenedTree = (nodes, parents = []) => {
const flattenedTree = [];
const flattenNodes = [];

for (const node of nodes) {
flattenNodes.push({node, parents});
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could be

const flattenNodes = nodes.map((node) => {node, parents});


while (flattenNodes.length > 0) {
const {node, parents} = flattenNodes.pop();

const deepness = parents.length;
const nodeWithHelpers = {...node, deepness, parents};

if (!nodeHasChildren(node) || !isNodeExpanded(node)) {
return [...flattenedTree, nodeWithHelpers];
flattenedTree.push(nodeWithHelpers);

if (nodeHasChildren(node) && isNodeExpanded(node)) {
const childParents = [...parents, node.id];

for (let i = node.children.length - 1; i >= 0; i--) {
flattenNodes.push({node: node.children[i], parents: childParents});
}
}
}

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

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