mirror of
https://github.com/carbon-design-system/carbon-components-svelte.git
synced 2025-09-14 18:01:06 +00:00
fix(to-hierarchy): revert to previous implementation
This commit is contained in:
parent
56da2b408b
commit
96d37cc490
1 changed files with 25 additions and 12 deletions
|
@ -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;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue