Multi-dimensional array walker with observation
  • JavaScript 100%
Find a file
2016-07-03 10:18:38 -04:00
spec Add object context parameter 2016-07-03 10:16:39 -04:00
.gitattributes :neckbeard: Added .gitattributes & .gitignore files 2016-06-28 20:29:51 -04:00
.gitignore :neckbeard: Added .gitattributes & .gitignore files 2016-06-28 20:29:51 -04:00
index.js Add object context parameter 2016-07-03 10:16:39 -04:00
LICENSE.md Setup module. 2016-06-28 21:44:53 -04:00
package.json 1.1.0 2016-07-03 10:18:38 -04:00
README.md Add object context parameter 2016-07-03 10:16:39 -04:00

Array Walker

Traverses a multi-dimensional array and fires off a callback with a value and its relationship.

Example

let walker = require('array-walker');

// A single-dimensional array
walker(['a', 'b'], (value, key) => console.log(value, key));
// a, 0
// b, 1

// A two-dimensional array
walker([['a', 'b'], ['c', 'd']], (value, x, y) => console.log(value, x, y));
// a, 0, 0
// b, 0, 1
// c, 1, 0
// d, 1, 1

// A 12-dimensional array
walker(
  [[[[[[[[[[[['a', 'b']]]]]], 'c']]]]]],
  (value, ...lineage) => console.log(value, ...lineage)
);
// a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
// b, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
// c, 0, 0, 0, 0, 0, 1


// With context
walker(['a', 'b'], callbackWithContext, {example: "The Answer"});
// The Answer, a, 0
// The Answer, b, 1

function callbackWithContext(value, key) {
  console.log(this.example, value, key);
}

Installation

$ npm install array-walker

API

var walker = require('array-walker');

walker(items, observationCallback, context, ...lineage)

Type Data Type Name Description
parameter *[] items The array to walk.
parameter function observationCallback The function to call when a non-array value is found.
parameter * The context passed to the callback
parameter ...number [lineage] The parent indexes.
returns undefined n/a n/a

observationCallback(value, ...lineage)

The observation callback is fired when a non-array value is found.

Type Data Type Name Description
this * this The context passed to the walker
parameter !*[] value The value that was discovered.
parameter ...number lineage The indexes in each dimension of the array.
returns undefined n/a n/a