(flatList: { type: string, path: string }[])
| 47 | |
| 48 | |
| 49 | export const buildFileTree = (flatList: { type: string, path: string }[]): FileTreeNode => { |
| 50 | const root: FileTreeNode = { |
| 51 | name: 'root', |
| 52 | path: '', |
| 53 | type: 'tree', |
| 54 | children: [], |
| 55 | }; |
| 56 | |
| 57 | for (const item of flatList) { |
| 58 | const parts = item.path.split('/'); |
| 59 | let current: FileTreeNode = root; |
| 60 | |
| 61 | for (let i = 0; i < parts.length; i++) { |
| 62 | const part = parts[i]; |
| 63 | const isLeaf = i === parts.length - 1; |
| 64 | const nodeType = isLeaf ? item.type : 'tree'; |
| 65 | let next = current.children.find((child: FileTreeNode) => child.name === part && child.type === nodeType); |
| 66 | |
| 67 | if (!next) { |
| 68 | next = { |
| 69 | name: part, |
| 70 | path: item.path, |
| 71 | type: nodeType, |
| 72 | children: [], |
| 73 | }; |
| 74 | current.children.push(next); |
| 75 | } |
| 76 | current = next; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | const sortTree = (node: FileTreeNode): FileTreeNode => { |
| 81 | if (node.type === 'blob') { |
| 82 | return node; |
| 83 | } |
| 84 | |
| 85 | const sortedChildren = node.children |
| 86 | .map(sortTree) |
| 87 | .sort(compareFileTreeItems); |
| 88 | |
| 89 | return { |
| 90 | ...node, |
| 91 | children: sortedChildren, |
| 92 | }; |
| 93 | }; |
| 94 | |
| 95 | return sortTree(root); |
| 96 | } |
no test coverage detected