1.1.8 • Published 4 days ago

to-path-tree v1.1.8

Weekly downloads
-
License
MIT
Repository
github
Last release
4 days ago

to-path-tree

Convert a file path array to a tree.

Installation

pnpm i to-path-tree

Usage

Function usage

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

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 items under 'src/a/'

Tree types

The data structure of the tree is as follows:

export interface NodeItem<T> {
  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<T>
}

export interface TreeNode<T> {
  items: NodeItem<T>[]
  name: string
  path: string
  /**
   * Relative to parent path
   */
  relativePath: string
  /**
   * Relative to root path, exclude sep
   */
  relativePathName: string
  subDirectory: {
    [key: string]: TreeNode<T>
  } | null
  parent?: TreeNode<T>
}

Traverse the tree

You can use walkPathTree to traverse the tree.

For example:

import { pathToTree, walkPathTree } from 'to-path-tree'

const tree = pathToTree(input)
walkPathTree(tree, (node) => {
  for (const item of node.items) {
    if (item.path === 'src/a/b/d/index.ts') {
      // do something...
    }
  }
})

License

MIT

1.1.8

4 days ago

1.1.7

11 days ago

1.1.1

13 days ago

1.1.0

13 days ago

1.0.0

13 days ago

1.1.6

13 days ago

1.1.5

13 days ago

1.1.4

13 days ago

1.1.3

13 days ago

1.1.2

13 days ago

0.2.1

5 months ago

0.2.0

9 months ago

0.1.6

9 months ago

0.1.5

9 months ago

0.1.4

9 months ago

0.1.3

9 months ago

0.1.2

9 months ago

0.1.1

9 months ago

0.1.0

9 months ago