1.1.0 • Published 8 years ago

array-walker v1.1.0

Weekly downloads
3
License
ISC
Repository
github
Last release
8 years ago

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)

TypeData TypeNameDescription
parameter*[]itemsThe array to walk.
parameterfunctionobservationCallbackThe function to call when a non-array value is found.
parameter*The context passed to the callback
parameter...numberlineageThe parent indexes.
returnsundefinedn/an/a

observationCallback(value, ...lineage)

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

TypeData TypeNameDescription
this*thisThe context passed to the walker
parameter!*[]valueThe value that was discovered.
parameter...numberlineageThe indexes in each dimension of the array.
returnsundefinedn/an/a

Links