controlled-loop.js

Version:
  • 2.0.1
License:

A javascript module for moving forward, backward, and in a non-linear fashion through an array or object one or more keys at a time.

Creating a controlled-loop allows you to move through an array or object in many different ways

  1. iterate similar to generators with next()
  2. backup with previous()
  3. run in bulk like a forEach() but with the ability to stop at any time
  4. chunk or batch a group of items at a time
  5. iterate over every nth item
  6. iterate in reverse
  7. reverse direction mid-flow
  8. skip over items
  9. goto a specific key
  10. Set your own "keys" array to only use a subset of properties or to set the order
  11. change the callback at any time

Installing

GitHub

https://github.com/bartmelton/ControlledLoop

NPM

npm install controlled-loop

Bower

bower install controlled-loop

Terminology:

because you can move forward (0 to n) or in reverse (n to 0) the terms forward and backward can get confusing.

  • the term forward implies the action of next(), regardless of whether you are moving in reverse or not.
  • the term backwards implies the action of previous(), regardless of whether you are moving in reverse or not.
  • When operating normally (0-n), forward (next()) would be +1 and backwards (previous()) would be -1.
  • When operating in reverse (n-0), forward (next()) would be -1 and backwards (previous()) would be +1.

Exports:

  1. It will export as an AMD module if available, otherwise it will try to export as a CommonJS module
  2. If Lodash or Underscore are available, it adds as a mixin.
  3. If none of the above options are available it falls back to a global controlledLoop function attached to window, global, or this depending on which is available.

Examples

Node

var controlledLoop = require("controlled-loop").controlledLoop

Lodash/Underscore

_.controlledLoop()

default

controlledLoop();