forked from khtdr/treeify-paths
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.ts
42 lines (37 loc) · 902 Bytes
/
lib.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
39
40
41
export class Node {
constructor(
public path: string = '',
) {}
name: string = '';
children: Node[] = [];
};
function fill (node:Node, paths:string[]) {
let cMap = {};
paths.forEach(file => {
let parts = file.split('/');
if (!cMap[parts[0]]) {
let fullPath = node.path + '/' + parts[0];
cMap[parts[0]] = {
paths:[],
obj: new Node(fullPath.replace(/^\//, ''))
};
}
if (parts.length == 1) {
cMap[parts[0]].obj.name = parts[0];
} else {
let dir = parts.shift();
let rest = parts.join('/');
cMap[dir].paths.push(rest);
}
});
let keys = Object.keys(cMap);
keys.sort();
keys.forEach(key => {
fill(cMap[key].obj, cMap[key].paths)
node.children.push(cMap[key].obj);
});
return node;
}
export default function treeifyPaths (paths: string[] = []): Node {
return fill(new Node, paths);
}