Skip to content

emilbayes/depth-first-map

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

depth-first-map

Map a tree of arrays in pre-order depth-first

Usage

var dfs = require('depth-first-map')

// Numbers refer to the order in which fn touches the elements
var tree = [
  0,
  1,
  // outer array: 2, inner array: 4
  [3, [5]],
  6
]

dfs(tree, x => x)

API

var newTree = dfs(tree, fn, context)

Map tree to newTree calling fn(subtree, depth, index), where context (this) will be to the current subtree, unless defined in which case it will stay constant through out the traversal. Please review the following control flow symbols as well for more powerful mapping possibilities.

return dfs.continue

Skip the current element, but continue processing siblings

return dfs.break

Break out of processing the current element, preserving previously maped siblings.

return dfs.drop

Drop the current subtree and return back to processing parent. Previously maped siblings will also be dropped.

return dfs.spread(elms)

Return an array of new elements to be spliced into position of the current subtree / leaf. The next iteration will process the first element of the spread elements:

dfs([5], x => x > 1 ? dfs.spread([1, x - 1]) : 1) // => [1, 1, 1, 1, 1]
/*
[5] => [1, 4] => [1, 1, 3] => [1, 1, 1, 2] => [1, 1, 1, 1, 1]
 */

Install

npm install depth-first-map

License

ISC

About

Map a tree of arrays in pre-order depth-first

Resources

License

Stars

Watchers

Forks

Packages

No packages published