(items: T[])
| 29 | * @returns A tree structure with children property |
| 30 | */ |
| 31 | export function convertFlatToTree<T extends { id: string; parentId: string }>(items: T[]): (T & { children: T[] })[] { |
| 32 | const itemMap = new Map<string, T & { children: T[] }>(); |
| 33 | const result: (T & { children: T[] })[] = []; |
| 34 | |
| 35 | // First pass: create a map of all items |
| 36 | for (const item of items) { |
| 37 | itemMap.set(item.id, { ...item, children: [] }); |
| 38 | } |
| 39 | |
| 40 | // Second pass: build the tree |
| 41 | for (const item of items) { |
| 42 | const node = itemMap.get(item.id); |
| 43 | if (!node) continue; |
| 44 | |
| 45 | if (item.parentId === "") { |
| 46 | result.push(node); |
| 47 | } else { |
| 48 | const parent = itemMap.get(item.parentId); |
| 49 | if (parent) { |
| 50 | parent.children.push(node); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | return result; |
| 56 | } |
no test coverage detected