Skip to content

Commit

Permalink
Perf: use itemsMap for lookup instead of Array.find
Browse files Browse the repository at this point in the history
  • Loading branch information
metonym committed Dec 9, 2024
1 parent d39fa97 commit 2087302
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
12 changes: 5 additions & 7 deletions src/utils/toHierarchy.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,28 @@
export function toHierarchy(flatArray, getParentId) {
/** @type {NodeLike[]} */
const tree = [];

// Use Map for O(1) lookups.
const childrenOf = new Map();
const itemsMap = new Map(flatArray.map(item => [item.id, item]));

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

// Only create nodes array if we have children
// Only create nodes array if we have children.
const children = childrenOf.get(item.id);
if (children) {
item.nodes = children;
}

// Check if parentId exists in the flatArray.
const parentExists = parentId && flatArray.some((p) => p.id === parentId);
// 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);

// If parent already processed, add nodes array.
const parent = flatArray.find((p) => p.id === parentId);
const parent = itemsMap.get(parentId);
if (parent) {
parent.nodes = childrenOf.get(parentId);
}
Expand Down
6 changes: 6 additions & 0 deletions tests/App.test.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script lang="ts">
import { TreeView as TreeViewNav } from "carbon-components-svelte";
import TreeView from "./TreeView/TreeView.test.svelte";
import TreeViewHierarchy from "./TreeView/TreeView.hierarchy.test.svelte";
import { onMount } from "svelte";
const routes = [
Expand All @@ -9,6 +10,11 @@
name: "TreeView",
component: TreeView,
},
{
path: "/treeview-hierarchy",
name: "TreeViewHierarchy",
component: TreeViewHierarchy,
},
] as const;
let currentPath = window.location.pathname;
Expand Down
File renamed without changes.

0 comments on commit 2087302

Please sign in to comment.