37 lines
840 B
JavaScript
37 lines
840 B
JavaScript
// Original source - https://stackoverflow.com/a/44681235
|
|
// Posted by le_m
|
|
// Retrieved 2026-03-11, License - CC BY-SA 3.0
|
|
// Insert path into directory tree structure:
|
|
//
|
|
//modified to construct an object instead of an array.
|
|
|
|
function insert(tree = {}, [head, ...tail]) {
|
|
|
|
if (tail.length > 0) {
|
|
tree[head] = insert(tree[head], tail)
|
|
} else {
|
|
tree[head] = true
|
|
}
|
|
|
|
return tree;
|
|
}
|
|
|
|
// Example:
|
|
let examplepaths = [
|
|
'css/style.css',
|
|
'about/bird.svg',
|
|
];
|
|
|
|
//naive! assumes relative path like in example.
|
|
//A more robust implementation would need to resolve paths first, but to what.
|
|
export default function process(paths) {
|
|
return paths
|
|
.map(path => path.split('/')
|
|
//.slice(1) //if path starts with / or ./
|
|
)
|
|
.reduce((tree, path) => insert(tree, path), {});
|
|
}
|
|
|
|
//test:
|
|
// console.log(process(examplepaths));
|