npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

tree-crawl

v1.2.2

Published

Agnostic tree traversal library.

Downloads

30,255

Readme

tree-crawl travis codecov greenkeeper size

Agnostic tree traversal library.

  • Agnostic: Supports any kind of tree. You provide a way to access a node's children, that's it.
  • Fast: Crafted to be optimizer-friendly. See performance for more details.
  • Mutation friendly: Does not 💥 when you mutate the tree.
  • Multiple orders: Supports DFS pre and post order and BFS traversals.

Quickstart

Installation

You can install tree-crawl with yarn:

$ yarn add tree-crawl

Alternatively using npm:

$ npm install --save tree-crawl

Usage

import crawl from 'tree-crawl'

// traverse the tree in pre-order
crawl(tree, console.log)
crawl(tree, console.log, { order: 'pre' })

// traverse the tree in post-order
crawl(tree, console.log, { order: 'post' })

// traverse the tree using `childNodes` as the children key
crawl(tree, console.log, { getChildren: node => node.childNodes })

// skip a node and its children
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    context.skip()
  }
})

// stop the walk
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    context.break()
  }
})

// remove a node
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    context.parent.children.splice(context.index, 1)
    context.remove()
  }
})

// replace a node
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    const node = {
      type: 'new node',
      children: [
        { type: 'new leaf' }
      ]
    }
    context.parent.children[context.index] = node
    context.replace(node)
  }
})

FAQ

How can I get the path of the current node (#37)?

tl;dr It's easy for DFS, less easy for BFS

If you are using DFS you can use the following utility function:

const getPath = context =>
  context.cursor.stack.xs.reduce((path, item) => {
    if (item.node) {
      path.push(item.node)
    }
    return path
  }, [])

If you are really concerned about performance, you could read items from the stack directly. Each item has a node and index property that you can use. The first item in the stack can be discarded and will have a node set to null. Be aware that you should not mutate the stack, or it will break the traversal.

If you are using BFS, things gets more complex. A simple hacky way to do so is to traverse the tree using DFS first. You can ad a path property to your nodes using the method above. And then do your regular BFS traversal using that path property.

API

Iteratee

Called on each node of the tree.

Type: Function

Parameters

Options

Walk options.

Type: Object

Parameters

  • node

Properties

  • getChildren Function? Return a node's children.
  • order ("pre" | "post" | "bfs")? Order of the walk either in DFS pre or post order, or BFS.

Examples

Traverse a DOM tree.

crawl(document.body, doSomeStuff, { getChildren: node => node.childNodes })

BFS traversal

crawl(root, doSomeStuff, { order: 'bfs' })

crawl

Walk a tree recursively.

By default getChildren will return the children property of a node.

Parameters

  • root Object Root node of the tree to be walked.
  • iteratee Iteratee Function invoked on each node.
  • options Options? Options customizing the walk.

Context

A traversal context.

Four operations are available. Note that depending on the traversal order, some operations have no effects.

Parameters

  • flags Flags
  • cursor Cursor

skip

Skip current node, children won't be visited.

Examples

crawl(root, (node, context) => {
  if ('foo' === node.type) {
    context.skip()
  }
})

break

Stop traversal now.

Examples

crawl(root, (node, context) => {
  if ('foo' === node.type) {
    context.break()
  }
})

remove

Notifies that the current node has been removed, children won't be visited.

Because tree-crawl has no idea about the intrinsic structure of your tree, you have to remove the node yourself. Context#remove only notifies the traversal code that the structure of the tree has changed.

Examples

crawl(root, (node, context) => {
  if ('foo' === node.type) {
    context.parent.children.splice(context.index, 1)
    context.remove()
  }
})

replace

Notifies that the current node has been replaced, the new node's children will be visited instead.

Because tree-crawl has no idea about the intrinsic structure of your tree, you have to replace the node yourself. Context#replace notifies the traversal code that the structure of the tree has changed.

Parameters

Examples

crawl(root, (node, context) => {
  if ('foo' === node.type) {
    const node = {
      type: 'new node',
      children: [
        { type: 'new leaf' }
      ]
    }
    context.parent.children[context.index] = node
    context.replace(node)
  }
})

parent

Get the parent of the current node.

Returns Object Parent node.

depth

Get the depth of the current node. The depth is the number of ancestors the current node has.

Returns Number Depth.

level

Get the level of current node. The level is the number of ancestors+1 the current node has.

Returns Number Level.

index

Get the index of the current node.

Returns Number Node's index.

Performance

tree-crawl is built to be super fast and traverse potentially huge trees. It's possible because it implements its own stack and queue for traversal algorithms and makes sure the code is optimizable by the VM.

If you do need real good performance please consider reading this checklist first.

Your main objective is to keep the traversal code optimized and avoid de-optimizations and bailouts. To do so, your nodes should have the same hidden class and your code stay monomorphic.

Related

License

MIT © Nicolas Gryman