-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtree.ts
38 lines (37 loc) · 814 Bytes
/
tree.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
export type TreeNode = { name: string } & ({
kind: 'folder',
children: TreeNode[],
} | {
kind: 'file',
});
export const buildTree = (list: string[]) => {
const tree: TreeNode[] = [];
const getFolder = (path: string[], t = tree) => {
for (const p of path) {
let f = t.find((x) => x.name === p);
if (!f) {
f = {
name: p,
kind: 'folder',
children: [],
};
t.push(f);
}
if (f.kind === 'file') {
throw new Error("Folder and file with same name");
}
t = f.children;
}
return t;
}
list
.forEach((x) => {
let sx = x.split('/');
const folder = getFolder(sx.slice(0, -1));
folder.push({
kind: 'file',
name: sx[sx.length - 1],
});
});
return tree;
};