fix(to-hierarchy): revert to previous implementation

This commit is contained in:
Eric Liu 2025-04-25 08:40:09 -07:00 committed by GitHub
commit 96d37cc490
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -13,22 +13,35 @@
export function toHierarchy(flatArray, getParentId) { export function toHierarchy(flatArray, getParentId) {
/** @type {NodeLike[]} */ /** @type {NodeLike[]} */
const tree = []; 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); const parentId = getParentId(item);
nodeMap.set(item.id, item);
if (!parentId || !nodeMap.has(parentId)) { // Only create nodes array if we have children.
tree.push(item); const children = childrenOf.get(item.id);
} else { if (children) {
const parent = nodeMap.get(parentId); item.nodes = children;
if (!parent.nodes) {
parent.nodes = [];
}
parent.nodes.push(item);
} }
}
// 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; return tree;
} }