diff --git a/src/utils/toHierarchy.js b/src/utils/toHierarchy.js index a0e7f32c17..3f9c70a09a 100644 --- a/src/utils/toHierarchy.js +++ b/src/utils/toHierarchy.js @@ -13,21 +13,20 @@ export function toHierarchy(flatArray, getParentId) { /** @type {NodeLike[]} */ const tree = []; - - // Use Map for O(1) lookups. const childrenOf = new Map(); + const itemsMap = new Map(flatArray.map(item => [item.id, item])); flatArray.forEach((item) => { const parentId = getParentId(item); - // Only create nodes array if we have children + // Only create nodes array if we have children. const children = childrenOf.get(item.id); if (children) { item.nodes = children; } - // Check if parentId exists in the flatArray. - const parentExists = parentId && flatArray.some((p) => p.id === parentId); + // Check if parentId exists using Map instead of array lookup. + const parentExists = parentId && itemsMap.has(parentId); if (parentId && parentExists) { if (!childrenOf.has(parentId)) { @@ -35,8 +34,7 @@ export function toHierarchy(flatArray, getParentId) { } childrenOf.get(parentId).push(item); - // If parent already processed, add nodes array. - const parent = flatArray.find((p) => p.id === parentId); + const parent = itemsMap.get(parentId); if (parent) { parent.nodes = childrenOf.get(parentId); } diff --git a/tests/App.test.svelte b/tests/App.test.svelte index de04ad2fe1..96c876d1f2 100644 --- a/tests/App.test.svelte +++ b/tests/App.test.svelte @@ -1,6 +1,7 @@