• Stars
    star
    130
  • Rank 277,575 (Top 6 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 5 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Walk any kind of tree structure depth- or breadth-first. Supports promises and advanced map-reduce operations with a very small API.

treeverse

Walk any kind of tree structure depth- or breadth-first. Supports promises and advanced map-reduce operations with a very small API.

Treeverse does not care what kind of tree it is, it will traverse it for you just fine. It does the right thing with functions that return Promises, and returns a non-Promise value if your functions don't return Promises.

Rather than imposing a specific structure, like requiring you to have child nodes stored in a children array, it calls the supplied getChildren() function, so the children can be anywhere (or not even exist yet!) This makes it suitable for creating an optimized tree from a set of dependency manifests, for example.

USAGE

const {depth, breadth} = require('treeverse')

// depth-first traversal
// returns a promise if any visit/leave function returns a promise
// otherwise returns the result of leave, or visit if no leave function
// provided.
depth({
  // the root node where we start the traversal
  tree: rootNode,

  visit (node) {
    // optional
    // called upon descent into the node.
    // return a promise, or a mapped value, or nothing to just leave it
    // as-is
  },
  leave (node, children) {
    // optional
    // called as we ascend back to the root of the tree.
    // return a promise, or a reduced value, or nothing to leave it as is
    // the children array is a list of the child nodes that have been
    // visited (and potentially left) already.  If the tree is acyclic,
    // then leave() will have been called on all of them.  If it has
    // cycles, then the children may not have been left yet.
  },
  getChildren (node, nodeResult) {
    // required
    // return an array of child nodes in the tree, if any exist
    // returning a promise is totally ok, of course.
    // the first argument is the original value of the node.  The second
    // argument is the result of visit(node).
  },
  filter (node) {
    // optional
    // return true if the node should be visited, false otherwise
    // initial tree is always visited, so this only filters children
    // note that filtering a node _also_ filters all of its children.
  },
})

// breadth first traversal
// returns a promise if any visit function returns a promise
// otherwise returns the result of the top-level node.
// note that only a visit() function is supported here, since a node's
// children are typically traversed much later in the process.
breadth({
  // the root node where we start the traversal
  tree: rootNode,

  visit (node) {
    // optional, but a no-op if not provided.
    // called when this node is encountered in the traversal.
    // return a promise, or a mapped value, or nothing to leave as-is.
  },
  getChildren (node, nodeResult) {
    // required, same as depth()
  },
  filter (node) {
    // optional, same as depth()
  },
})

API

Both functions take a single options object as an argument, and return either the result value, or a Promise to the result value if the methods in the options argument ever return a Promise.

  • treeverse.breadth - Perform a breadth-first traversal. That is, walk across node siblings before traversing node children.
  • treeverse.depth - Perform a depth-first traversal. That is, walk down into child nodes before traversing siblings.

OPTIONS

All function options can return a Promise or actual value.

The return value is the result of the top level visit function if no leave function is provided, or leave. If any method along the way returns a promise, then the top level function will return a promise which resolves to the result of visiting (and leaving) the top node in the tree.

  • tree - The initial node where the traversal begins.
  • visit(node) - Function to call upon visiting a node.
  • leave(node, children) - (Depth only) Function to call upon leaving a node, once all of its children have been visited, and potentially left. children is an array of child node visit results. If the graph is cyclic, then some children may have been visited but not left.
  • getChildren(node, nodeResult) - Get an array of child nodes to process.
  • filter - Filter out child nodes from the traversal. Note that this filters the entire branch of the tree, not just that one node. That is, children of filtered nodes are not traversed either.

STACK DEPTH WARNING

When a leave method is specified, then recursion is used, because maintaining state otherwise is challenging. This means that using leave with a synchronous depth first traversal of very deeply nested trees will result in stack overflow errors.

To avoid this, either make one or more of the functions async, or do all of the work in the visit method.

Breadth-first traversal always uses a loop, and is stack-safe.

It is possible to implement depth first traversal with a leave method using a loop rather than recursion, but maintaining the leave(node, [children]) API surface would be challenging, and is not implemented at this time.

More Repositories

1

node-glob

glob functionality for node.js
TypeScript
8,123
star
2

rimraf

A `rm -rf` util for nodejs
JavaScript
5,309
star
3

node-lru-cache

A fast cache that automatically deletes the least recently used items
TypeScript
4,844
star
4

minimatch

a glob matcher in javascript
JavaScript
3,074
star
5

github

Just a place to track issues and feature requests that I have for github
2,209
star
6

nave

Virtual Environments for Node
Shell
1,580
star
7

node-graceful-fs

fs with incremental backoff on EMFILE
JavaScript
1,267
star
8

sax-js

A sax style parser for JS
JavaScript
1,046
star
9

tshy

JavaScript
847
star
10

node-tar

tar for node
JavaScript
755
star
11

st

A node module for serving static files. Does etags, caching, etc.
JavaScript
376
star
12

inherits

Easy simple tiny inheritance in JavaScript
JavaScript
352
star
13

cluster-master

Take advantage of node built-in cluster module behavior
JavaScript
276
star
14

minipass

A stream implementation that does more by doing less
TypeScript
246
star
15

once

Run a function exactly one time
JavaScript
216
star
16

yallist

Yet Another Linked List
JavaScript
198
star
17

server-destroy

When close() is just not enough
JavaScript
184
star
18

ttlcache

TypeScript
155
star
19

semicolons

When you require("semicolons"), THEY ARE REQUIRED.
JavaScript
145
star
20

slide-flow-control

A flow control library that fits in a slideshow
JavaScript
134
star
21

multipart-js

JavaScript
123
star
22

reading-list

a list of books I recommend
121
star
23

node-touch

touch(1) for node
JavaScript
121
star
24

catcher

TypeScript
119
star
25

async-cache

Cache your async lookups and don't fetch the same thing more than necessary.
JavaScript
119
star
26

core-util-is

The util.is* functions from Node core
JavaScript
98
star
27

dezalgo

Contain async insanity so that the dark pony lord doesn't eat souls
JavaScript
89
star
28

github-flavored-markdown

Deprecated. Use marked instead.
JavaScript
79
star
29

minizlib

A smaller, faster, zlib stream built on http://npm.im/minipass and Node.js's zlib binding.
JavaScript
71
star
30

node-bench

JavaScript
71
star
31

free-as-in-hugs-license

A (Not OSI-Approved) software license you may use if you wish
70
star
32

sigmund

Quick and dirty psychoanalysis for objects
JavaScript
67
star
33

inflight

Add callbacks to requests in flight to avoid async duplication
JavaScript
66
star
34

fast-list

A fast O(1) push/pop/shift/unshift thing
JavaScript
66
star
35

gist-cli

A gist cli client written in Node
JavaScript
64
star
36

dotfiles

My Dot Files
Shell
63
star
37

wrappy

Callback wrapping utility
JavaScript
56
star
38

block-stream

A stream of fixed-size blocks
JavaScript
52
star
39

isexe

Minimal module to check if a file is executable.
TypeScript
48
star
40

.vim

My vim settings
Vim Script
47
star
41

jackspeak

A very strict and proper argument parser.
TypeScript
44
star
42

char-spinner

Put a little spinner on process.stderr, as unobtrusively as possible.
JavaScript
43
star
43

st-example

an example of serving static files easily in node using the st module
JavaScript
40
star
44

templar

A lightweight template thing for node http servers
JavaScript
37
star
45

nosync

Prevent sync functions in your node programs after first tick
JavaScript
37
star
46

use-strict

Makes all subsequent modules in Node get loaded in strict mode.
JavaScript
37
star
47

path-scurry

TypeScript
35
star
48

ssh-key-decrypt

Decrypt and encrypted ssh private keys
JavaScript
35
star
49

ejsgi

Like JSGI, but using streams.
JavaScript
35
star
50

node-eliza

A Robotic Rogerian Therapist, on IRC
JavaScript
34
star
51

natives

Do stuff with Node.js's native JavaScript modules
JavaScript
31
star
52

goosh

Front-end old-style terminal interface, for web services like those provided by Google and Yahoo.
JavaScript
31
star
53

simple-node-server

A simple fast node http server toolkit.
JavaScript
30
star
54

util-extend

Node's internal object extension function, for you!
JavaScript
30
star
55

chownr

Like `chown -R`
JavaScript
28
star
56

csrf-lite

CSRF protection utility for framework-free node sites.
JavaScript
28
star
57

chmodr

Like `chmod -R` in node
JavaScript
28
star
58

node-hexedit

hexadecimal editor in node
JavaScript
27
star
59

back-to-markdown.css

Turns any markdown editor into a WYSIWYG editor
CSS
26
star
60

node-async-simple

Multiply two numbers, slowly, on the thread pool.
C++
26
star
61

json-stringify-nice

Stringify an object sorting scalars before objects, and defaulting to 2-space indent
JavaScript
25
star
62

node-strict

Makes your Node programs strict about stuff when loaded
JavaScript
25
star
63

fs.realpath

Use node's fs.realpath, but fall back to the JS implementation if the native one fails
JavaScript
25
star
64

sock-daemon

TypeScript
24
star
65

promise-all-reject-late

Like Promise.all, but save rejections until all promises are resolved
JavaScript
24
star
66

promise-call-limit

Call an array of promise-returning functions, restricting concurrency to a specified limit.
TypeScript
24
star
67

node6-module-system-change

A demonstration of what changed in node 6's module loading logic
JavaScript
24
star
68

color-support

A module which will endeavor to guess your terminal's level of color support.
JavaScript
24
star
69

polite-json

TypeScript
23
star
70

ircretary

A note-taking IRC bot
JavaScript
23
star
71

yamlish

A parser for the yamlish format
JavaScript
22
star
72

fs-minipass

fs read and write streams based on minipass
JavaScript
21
star
73

pseudomap

Like `new Map` but for older JavaScripts
JavaScript
21
star
74

node-fuse

Fuse bindings for nodejs
21
star
75

slocket

A locking socket alternative to file-system mutex locks
JavaScript
21
star
76

proto-list

A list of objects bound by prototype chain
JavaScript
20
star
77

retry-until

A function that will keep running a function you give it as long as it throws for a period of time
JavaScript
20
star
78

node-srand

srand bindings for node - Seedable predictable pseudorandom number generator
C++
20
star
79

mutate-fs

Mutate the Node.js filesystem behavior for tests.
JavaScript
20
star
80

ryp

Featureless npm-package bundling.
Shell
19
star
81

filewatcherthing

a thing to watch a file and then run a command
JavaScript
19
star
82

gatsby-remark-tumble-media

A plugin for gatsby-transformer-remark to support photosets, video, and audio in markdown frontmatter.
JavaScript
19
star
83

sodn

SOcial DNodes
JavaScript
19
star
84

joyent-node-on-smart-example

A blog post.
JavaScript
18
star
85

error-page

Easily send errors in Node.js HTTP servers. Think like the `ErrorDocument` declarations in Apache config files.
JavaScript
17
star
86

_ify

an itty bitty curry utility
JavaScript
17
star
87

url-parse-as-address

Parse a URL assuming that it's http/https, even if protocol or // isn't present
JavaScript
17
star
88

http-https

A wrapper that chooses http or https for requests
JavaScript
17
star
89

perfalize

TypeScript
16
star
90

cssmin

A cross-platform regular-expression based minifier for CSS
16
star
91

duplex-passthrough

like a passthrough, but in both directions
JavaScript
16
star
92

mintee

a tiny module for piping an input to multiple output streams
JavaScript
16
star
93

create-isaacs

An npm init module to create modules like I do
JavaScript
16
star
94

tap-assert

An assert module that outputs tap result objects
JavaScript
16
star
95

domain-http-server

A module thingie to use domains in Express or Restify or just regular HTTP servers
JavaScript
15
star
96

fs-readstream-seek

A fs.ReadStream that supports seeking to arbtrary locations within a file.
JavaScript
15
star
97

canonical-host

Node module to redirect users to the canonical hostname for your site.
JavaScript
15
star
98

mcouch

Put your CouchDB in Manta, attachments and docs and all
JavaScript
14
star
99

hardhttps

Slightly hardened https for node
JavaScript
14
star
100

exit-code

`process.exitCode` behavior back-ported from io.js and Node.js 0.12+
JavaScript
14
star