This module helps interacting with Tree
structures in TypeScript. It is optimized to work with big trees without causing overflows. Therefore it doesn't use recursion and the implementations for preOrder
and postOrder
traversals use Promise.all
for concurrency to traverse multiple nodes at ones.
It is fully typed and has over 95% test coverage.
๐ Zero dependency
๐ท๏ธ Fully typed
โจ Optimized for big trees
๐ง No recursion -> no memory overflows
๐ค Small bundle size
To install the module, run the following command:
# pnpm
pnpm install @itpropro/tree-structure-ts
# npm
npm install @itpropro/tree-structure-ts
# yarn
yarn add @itpropro/tree-structure-ts
// ESM / TypeScript
import { Tree } from '@itpropro/tree-structure-ts'
import type { TreeNode } from '@itpropro/tree-structure-ts'
To create a new Tree
instance, use the Tree
constructor:
const tree = new Tree('root')
const root = tree.root
To add a child node to a TreeNode, use the addChild method:
const child1 = root.addChild('child1')
const child2 = root.addChild('child2')
To get all nodes in the tree below a TreeNode, use the all method:
const nodes = root.all()
To traverse a tree, use the traverse method:
root.traverse((node) => {
// This function is called for each node in the tree
})
You can specify the traversal order by passing one of the following values to the traverse method:
- breadthFirst (the default): visits nodes in breadth-first order
- depthFirst: visits nodes in depth-first order
- preOrder: visits the current node, then traverses the left subtree, then traverses the right subtree
- postOrder: traverses the left subtree, then traverses the right subtree, then visits the current node
for all avalaible methods and fields, please read the detailed documentation of the Tree
and TreeNode
class: Class docs.
See Contributing Guide.
Made with โค๏ธ
Published under MIT License.