Skip to content

Commit 2087302

Browse files
committed
Perf: use itemsMap for lookup instead of Array.find
1 parent d39fa97 commit 2087302

File tree

3 files changed

+11
-7
lines changed

3 files changed

+11
-7
lines changed

src/utils/toHierarchy.js

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,30 +13,28 @@
1313
export function toHierarchy(flatArray, getParentId) {
1414
/** @type {NodeLike[]} */
1515
const tree = [];
16-
17-
// Use Map for O(1) lookups.
1816
const childrenOf = new Map();
17+
const itemsMap = new Map(flatArray.map(item => [item.id, item]));
1918

2019
flatArray.forEach((item) => {
2120
const parentId = getParentId(item);
2221

23-
// Only create nodes array if we have children
22+
// Only create nodes array if we have children.
2423
const children = childrenOf.get(item.id);
2524
if (children) {
2625
item.nodes = children;
2726
}
2827

29-
// Check if parentId exists in the flatArray.
30-
const parentExists = parentId && flatArray.some((p) => p.id === parentId);
28+
// Check if parentId exists using Map instead of array lookup.
29+
const parentExists = parentId && itemsMap.has(parentId);
3130

3231
if (parentId && parentExists) {
3332
if (!childrenOf.has(parentId)) {
3433
childrenOf.set(parentId, []);
3534
}
3635
childrenOf.get(parentId).push(item);
3736

38-
// If parent already processed, add nodes array.
39-
const parent = flatArray.find((p) => p.id === parentId);
37+
const parent = itemsMap.get(parentId);
4038
if (parent) {
4139
parent.nodes = childrenOf.get(parentId);
4240
}

tests/App.test.svelte

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<script lang="ts">
22
import { TreeView as TreeViewNav } from "carbon-components-svelte";
33
import TreeView from "./TreeView/TreeView.test.svelte";
4+
import TreeViewHierarchy from "./TreeView/TreeView.hierarchy.test.svelte";
45
import { onMount } from "svelte";
56
67
const routes = [
@@ -9,6 +10,11 @@
910
name: "TreeView",
1011
component: TreeView,
1112
},
13+
{
14+
path: "/treeview-hierarchy",
15+
name: "TreeViewHierarchy",
16+
component: TreeViewHierarchy,
17+
},
1218
] as const;
1319
1420
let currentPath = window.location.pathname;

0 commit comments

Comments
 (0)