Skip to content

itpropro/tree-structure-ts

Repository files navigation

@itpropro/tree-structure-ts

npm (scoped) npm bundle size (scoped) ci Code Coverage

Introduction

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

Quick Start

Installation

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

Import

// ESM / TypeScript
import { Tree } from '@itpropro/tree-structure-ts'
import type { TreeNode } from '@itpropro/tree-structure-ts'

Usage

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.

Contribution

See Contributing Guide.

License

Made with ❤️

Published under MIT License.

About

Library for creating and interacting with tree structures, written in TypeScript.

Resources

License

Stars

Watchers

Forks

Packages

No packages published