File tree Expand file tree Collapse file tree 3 files changed +11
-7
lines changed Expand file tree Collapse file tree 3 files changed +11
-7
lines changed Original file line number Diff line number Diff line change 13
13
export function toHierarchy ( flatArray , getParentId ) {
14
14
/** @type {NodeLike[] } */
15
15
const tree = [ ] ;
16
-
17
- // Use Map for O(1) lookups.
18
16
const childrenOf = new Map ( ) ;
17
+ const itemsMap = new Map ( flatArray . map ( item => [ item . id , item ] ) ) ;
19
18
20
19
flatArray . forEach ( ( item ) => {
21
20
const parentId = getParentId ( item ) ;
22
21
23
- // Only create nodes array if we have children
22
+ // Only create nodes array if we have children.
24
23
const children = childrenOf . get ( item . id ) ;
25
24
if ( children ) {
26
25
item . nodes = children ;
27
26
}
28
27
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 ) ;
31
30
32
31
if ( parentId && parentExists ) {
33
32
if ( ! childrenOf . has ( parentId ) ) {
34
33
childrenOf . set ( parentId , [ ] ) ;
35
34
}
36
35
childrenOf . get ( parentId ) . push ( item ) ;
37
36
38
- // If parent already processed, add nodes array.
39
- const parent = flatArray . find ( ( p ) => p . id === parentId ) ;
37
+ const parent = itemsMap . get ( parentId ) ;
40
38
if ( parent ) {
41
39
parent . nodes = childrenOf . get ( parentId ) ;
42
40
}
Original file line number Diff line number Diff line change 1
1
<script lang =" ts" >
2
2
import { TreeView as TreeViewNav } from " carbon-components-svelte" ;
3
3
import TreeView from " ./TreeView/TreeView.test.svelte" ;
4
+ import TreeViewHierarchy from " ./TreeView/TreeView.hierarchy.test.svelte" ;
4
5
import { onMount } from " svelte" ;
5
6
6
7
const routes = [
9
10
name: " TreeView" ,
10
11
component: TreeView ,
11
12
},
13
+ {
14
+ path: " /treeview-hierarchy" ,
15
+ name: " TreeViewHierarchy" ,
16
+ component: TreeViewHierarchy ,
17
+ },
12
18
] as const ;
13
19
14
20
let currentPath = window .location .pathname ;
File renamed without changes.
You can’t perform that action at this time.
0 commit comments