Introduction
Useful when converting a list of file names into a nested UL/LI tree. Perfect for site maps, and directory listings.
Provide a list of file names:
- blog/all.html
- blog/2036/overflows.html
And recieve a directory-like tree:
- blog
- all.html
- 2036
- overflows.html
Installation
Install it with NPM:
npm install --save treeify-paths
Import with modern syntax:
import treeifyPaths from "treeify-paths";
Or if you are not using NPM, install the library by downloading the source file directly and including it in your project:
curl -o treeify-paths.js "https://raw.githubusercontent.com/khtdr/treeify-paths/blob/master/dist/treeify-paths.js"
Load with classic syntax:
let treeify_paths = require("./treeify-paths").default;
The library itself is written in a few lines of typescript.
Example Usage
This module provides a function treeifyPaths
that takes a list of file names and returns a directory-like tree.
type Tree :{
path :string // full path to this node
name :string // name of this leaf
children :Tree[] // sub tree of trees and leaves
}
treeifyPaths(paths :string[]) => :Tree
This example produces prints the following output:
import treeifyPaths from 'treeify-paths';
console.log(JSON.stringify(treeifyPaths([
'about.html',
'careers',
'careers/job-1.html',
'careers/job-2.html',
'to/some/page.aspx',
]), null, 3);
{
"path": "",
"name": "",
"children": [
{
"path": "about.html",
"name": "about.html",
"children": []
},
{
"path": "careers",
"name": "careers",
"children": [
{
"path": "careers/job-1.html",
"name": "job-1.html",
"children": []
},
{
"path": "careers/job-2.html",
"name": "job-2.html",
"children": []
}
]
},
{
"path": "to",
"name": "",
"children": [
{
"path": "to/some",
"name": "",
"children": [
{
"path": "to/some/page.aspx",
"name": "page.aspx",
"children": []
}
]
}
]
}
]
}
Online Interactive Examples
Testing
The mocha tests have many examples
> treeify-paths@1.0.2 pretest khtdr/treeify-paths
> tsc lib.ts && mv lib.js treeify-paths.js
> treeify-paths@1.0.2 test khtdr/treeify-paths
> mocha tests.js
treeifyPaths([...arguments])
arguments: none
✓ should return an empty object
arguments: empty list
✓ should return an empty object
arguments: list with a single file
✓ should return a single file
✓ should return with nested children
arguments: multiple file names
✓ should return with nested children
✓ should alphabetize
✓ should ignore duplicates
7 passing (8ms)
The full source code and examples are available at: khtdr/treeify-paths