mirror of
https://github.com/carbon-design-system/carbon-components-svelte.git
synced 2025-09-15 10:21:05 +00:00
perf(to-hierarchy): optimize to use single-pass approach
This commit is contained in:
parent
a514f284e6
commit
dd41c977ed
1 changed files with 11 additions and 24 deletions
|
@ -13,35 +13,22 @@
|
||||||
export function toHierarchy(flatArray, getParentId) {
|
export function toHierarchy(flatArray, getParentId) {
|
||||||
/** @type {NodeLike[]} */
|
/** @type {NodeLike[]} */
|
||||||
const tree = [];
|
const tree = [];
|
||||||
const childrenOf = new Map();
|
const nodeMap = new Map();
|
||||||
const itemsMap = new Map(flatArray.map((item) => [item.id, item]));
|
|
||||||
|
|
||||||
flatArray.forEach((item) => {
|
for (const item of flatArray) {
|
||||||
const parentId = getParentId(item);
|
const parentId = getParentId(item);
|
||||||
|
nodeMap.set(item.id, item);
|
||||||
|
|
||||||
// Only create nodes array if we have children.
|
if (!parentId || !nodeMap.has(parentId)) {
|
||||||
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);
|
tree.push(item);
|
||||||
|
} else {
|
||||||
|
const parent = nodeMap.get(parentId);
|
||||||
|
if (!parent.nodes) {
|
||||||
|
parent.nodes = [];
|
||||||
|
}
|
||||||
|
parent.nodes.push(item);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
return tree;
|
return tree;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue