From 4e7c8b3001390fb1ff57aa25e888a0d8d65da9a8 Mon Sep 17 00:00:00 2001 From: Eric Liu Date: Thu, 24 Apr 2025 20:37:11 -0700 Subject: [PATCH] fix(to-hierarchy): revert to previous implementation Fixes #2157 --- src/utils/toHierarchy.js | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/utils/toHierarchy.js b/src/utils/toHierarchy.js index b8bd5c79..39f47b9e 100644 --- a/src/utils/toHierarchy.js +++ b/src/utils/toHierarchy.js @@ -13,22 +13,35 @@ export function toHierarchy(flatArray, getParentId) { /** @type {NodeLike[]} */ const tree = []; - const nodeMap = new Map(); + const childrenOf = new Map(); + const itemsMap = new Map(flatArray.map((item) => [item.id, item])); - for (const item of flatArray) { + flatArray.forEach((item) => { const parentId = getParentId(item); - nodeMap.set(item.id, item); - if (!parentId || !nodeMap.has(parentId)) { - tree.push(item); - } else { - const parent = nodeMap.get(parentId); - if (!parent.nodes) { - parent.nodes = []; - } - parent.nodes.push(item); + // Only create nodes array if we have children. + const children = childrenOf.get(item.id); + if (children) { + item.nodes = children; } - } + + // Check if parentId exists using Map instead of array lookup. + const parentExists = parentId && itemsMap.has(parentId); + + if (parentId && parentExists) { + if (!childrenOf.has(parentId)) { + childrenOf.set(parentId, []); + } + childrenOf.get(parentId).push(item); + + const parent = itemsMap.get(parentId); + if (parent) { + parent.nodes = childrenOf.get(parentId); + } + } else { + tree.push(item); + } + }); return tree; }