Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/alexzhang1030/to-path-tree
Convert a file path array to a tree.
https://github.com/alexzhang1030/to-path-tree
Last synced: 7 days ago
JSON representation
Convert a file path array to a tree.
- Host: GitHub
- URL: https://github.com/alexzhang1030/to-path-tree
- Owner: alexzhang1030
- License: mit
- Created: 2023-07-28T03:23:48.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-04-17T01:45:52.000Z (7 months ago)
- Last Synced: 2024-04-19T16:13:07.291Z (7 months ago)
- Language: TypeScript
- Size: 278 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# to-path-tree
Convert a file path array to a tree.
## Installation
```bash
pnpm i to-path-tree
```## Usage
### Function usage
```ts
import { pathToTree } from 'to-path-tree'const paths = [
'src/index.ts',
'src/a/index.ts',
'src/a/b/index.ts',
'src/a/b/d/index.ts',
'src/foo.ts',
'src/b/index.js',
'src/b/c/index.ts',
'a/index.ts',
'a/b.ts',
'a/b/index.js'
]const tree = pathToTree(paths)
```### Builder usage
```ts
import { PathTreeBuilder } from 'to-path-tree'const builder = new PathTreeBuilder()
builder.addPath('src/index.ts')
builder.addPath('src/a/index.ts')
builder.removePath('src/index.ts')
builder.getItems('src/a/') // get all file items under 'src/a/'
builder.getSubDirectories('src/') // get all subdirectories under 'src/'
```### Tree types
The data structure of the tree is as follows:
```ts
export interface NodeItem {
path: string
/**
* e.g. index
*/
filename: string
/**
* e.g. ts
*/
ext: string
/**
* e.g. index.ts
*/
file: string
data?: T
isEntry: boolean // the entry is index
parent: TreeNode
}export interface TreeNode {
items: NodeItem[]
name: string
/**
* This path is strict path, must start with sep, e.g. `/`
*/
path: string
/**
* Relative to parent path
*/
relativePath: string
/**
* Relative to root path, exclude sep
*/
relativePathName: string
subDirectory: {
[key: string]: TreeNode
} | null
parent?: TreeNode
}
```### Traverse the tree
You can use `walkPathTree` to traverse the tree.
For example:
```ts
import { pathToTree, walkPathTree } from 'to-path-tree'const tree = pathToTree(input)
walkPathTree(tree, (node) => {
for (const item of node.items) {
// NOTE: item.path is strict path, must start with sep, e.g. `/`
if (item.path === '/src/a/b/d/index.ts') {
// do something...
}
}
})
```## License
MIT