Giter Club home page Giter Club logo

tree-crawl's Introduction

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

  • node Object Node being visited.
  • context Context Traversal context

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

  • node Object Replacement node.

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

tree-crawl's People

Contributors

abhishiv avatar deltaidea avatar dependabot[bot] avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jameswlane avatar ngryman avatar tn1ck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

tree-crawl's Issues

Find node on value

I am trying this, but does not work:

const tree = [5, 8, -3, 10]

crawl(tree, (node, context) => {
  if (node.valueOf() > 6) {
    console.log('TEST WORKS')
  }
})

How should it be done?

Broken main entrypoint

This package does not work in Node.js without an ESM bundling tool like Rollup or Webpack.

The main field of package.json points to a non-existent dist/tree-crawl.node.js file. See here.

Node then falls back to index.js which has ESM import statements, which causes a crash.

a way to set `getChildren` to more than one condition?

I have a tree that sometime has a args property and sometimes has a content property. Is a way to set getChildren to more than one condition?

crawl(tree, n => console.log(n.type, n.value || n.op), {
  getChildren: node => node.args ||  node.content
});

A way to stop and resume the iteration

I have a case in which I would like to arbitrarily suspend and later resume the iteration. I have a large tree structure, traversing through which would take a very long time and I would like to do it in 16 ms time slices to not block the UI and give live preview of the effect of traversal.

You can see my project here: https://github.com/mcalus3/open-fraksl (tree-crawl is used for rendering fractal elements, number of which multiplies with every depth level, that's why there is so much of them).

It would be helpful if you guide me, show where to add such a function and I would like to add it myself, as a pull request :)

How to update the top level element?

I am trying to update the top level element and getting the below error as it is not the children of any element.
Uncaught TypeError: Cannot read property 'children' of undefined

The code i written is

const idToSearch = 1;
const updatedValue = 'updated value';
crawl(records, (node, context) => {
if (idToSearch.id === node.id) {
const updatedNode = node;
updatedNode.name = updatedValue;
context.parent.children[context.index] = updatedNode; // eslint-disable-line no-param-reassign,max-len
context.replace(node);
}
});

get Path like String

Hello, How can I get string path to node ?
like 'children[3].rows[0]' etc
Thx

Build ES6 Modules

I would like to use tree-crawl as an ES6 Module.
So far I have failed to build it โ€“ just changing the output format to 'es' does lead to a build error.

Add TypeScript types

Hey, this package does exactly what I need!
I'm using TypeScript, and although I can import JS directly, I'd like to have proper types for IntelliSense and stuff.

I'm happy to write the types myself. Would you be willing to integrate them into the repo? It's just an index.d.ts file in the root folder.
There're two alternatives: a file in the repo or a separate package @types/tree-crawl with that file if you don't want to officially support it.

GulpUglifyError: unable to minify JavaScript

I am getting 'GulpUglifyError: unable to minify JavaScript' when gulp is trying to minify tree-crawl. It may be happening because of the files in dist folder are in es6 and gulp uglify accepts es5 code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.