From b8dc2f5b7d90264e1c8a41bdbed03e5f7f57b22e Mon Sep 17 00:00:00 2001 From: Eric Liu Date: Fri, 22 Nov 2024 12:19:38 -0800 Subject: [PATCH] fix(tree-view): do not traverse original `nodes` --- src/TreeView/TreeView.svelte | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/TreeView/TreeView.svelte b/src/TreeView/TreeView.svelte index 260ba14510..7dad10fdf3 100644 --- a/src/TreeView/TreeView.svelte +++ b/src/TreeView/TreeView.svelte @@ -207,24 +207,22 @@ }); /** + * Recursively flattens a tree of nodes into a single array * @param {Array} nodes + * @returns {Array} */ function traverse(nodes) { - let _nodes = []; - - nodes.forEach((node) => { - _nodes.push(node); - - if (Array.isArray(node.nodes)) { - _nodes = [...nodes, ...traverse(node.nodes)]; + return nodes.reduce((acc, node) => { + acc.push(node); + if (Array.isArray(node.nodes) && node.nodes.length > 0) { + acc.push(...traverse(node.nodes)); } - }); - - return _nodes; + return acc; + }, []); } - $: nodes = traverse(nodes); - $: nodeIds = nodes.map((node) => node.id); + $: flattenedNodes = traverse(nodes); + $: nodeIds = flattenedNodes.map((node) => node.id); $: activeNodeId.set(activeId); $: selectedNodeIds.set(selectedIds); $: expandedNodeIds.set(expandedIds);