From 9c31348eec79f732bdba5f07fe253be9a357963e Mon Sep 17 00:00:00 2001 From: Joshua Wu Date: Fri, 16 Apr 2021 12:45:56 -0700 Subject: [PATCH] Iterative version of getFlattenedTree for improved performance --- src/selectors/getFlattenedTree.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/selectors/getFlattenedTree.js b/src/selectors/getFlattenedTree.js index e59d9a0..71b5902 100644 --- a/src/selectors/getFlattenedTree.js +++ b/src/selectors/getFlattenedTree.js @@ -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}); + } + + 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 = [];