"index.ts": "import {hello} from \"./hello\"\n\ntype TextNode = {\n name: string;\n body: string;\n};\n\ntype FileNode = {\n id: number;\n name: string;\n children?: FileNode[];\n};\n\nlet idCounter = 0; \nfunction buildFileTree(textNodes: TextNode[]): FileNode[] {\n const root: FileNode[] = []; \n textNodes.forEach((textNode) => {\n const pathParts = textNode.name.split('/'); \n insertNode(root, pathParts);\n });\n\n return root;\n}\n\nfunction insertNode(nodes: FileNode[], pathParts: string[]) {\n if (pathParts.length === 0) return; \n\n const name = pathParts[0]; \n let node = nodes.find((n) => n.name === name); \n\n if (!node) {\n \n node = { id: idCounter++, name: hello(name) };\n nodes.push(node); \n }\n\n if (pathParts.length > 1) {\n if (!node.children) {\n node.children = [];\n }\n insertNode(node.children, pathParts.slice(1)); }\n}\n\nconst textNodes: TextNode[] = [\n { name: \"/dir1/dir2/file1.txt\", body: \"Content of file1\" },\n { name: \"/dir1/dir2/file2.txt\", body: \"Content of file2\" },\n { name: \"/dir1/file3.txt\", body: \"Content of file3\" },\n { name: \"file4.txt\", body: \"Content of file4\" },\n];\n\nconst fileTree = buildFileTree(textNodes);\nconsole.log(JSON.stringify(fileTree, null, 2));",
0 commit comments