A lightweight trie implementation.

Usage no npm install needed!

<script type="module">
  import lighterTree from '';



Chat Version Downloads Build Coverage Style

The lighter-tree module is a lightweight trie data structure implementation. It can be used to build a structure of values, and perform a preorder traversal over all of the non-null values (including leaves which are not tree instances).


From your project directory, install and save as a dependency:

npm install --save lighter-tree



The lighter-tree module exports a constructor that extends the Type constructor from lighter-type. When a Type (such as Tree) is uppercased in documentation, it refers to the constructor or its constructor properties. And when a type is lowercased (such as tree), it refers to an instance and its prototype properties.


Tree is a constructor which instantiates tree objects. In documentation, A new tree object can be constructed simply with the new keyword.

var Tree = require('lighter-tree')

// Create a brand new Tree object.
var tree = new Tree()


If you would like to add tree functionality to an existing JavaScript object, you can use the init method to decorate it with Tree.prototype methods. It will be able to do everything a tree can do, without being an instance of Tree.

var Tree = require('lighter-tree')
var fs = require('fs')

// Mix tree functionality into the filesystem object.
var root = fs.branch('/')
var tmp = root.branch('/tmp')
//> /
//> /tmp
//> /tmp/a
//> /tmp/b


Tree instances can have an optional value, with the default being undefined. There is no requirement for the type of value, although the undefined type is handled in a special way, by triggering a function call when the tree's values are iterated with the each method.


Tree instances have an array of children, with the default being an empty array. Entries in the children array can have any type of value. If a child is an instance of Tree, it can be called a branch, otherwise, it is a leaf.


Adds a value into the array of children. If the value is an instance of Tree, it will be treated as a branch, otherwise, it will be treated as a leaf.


Creates a Tree instance with an optional value, and adds it to the tree instance's children, thereby making it a branch.


Iterates over a tree using preorder traversal, and calling fn(value, isLeaf) for each branch and leaf that has a defined value.

More on lighter-tree...