pfraces-graveyard / iterator

Extensible iteration system
0 stars 0 forks source link

alternative interface #1

Open pfraces opened 8 years ago

pfraces commented 8 years ago

Iterators are functions which iterate data returning each iteration as { value, index } (being index optional) each time is called and undefined when no more iterations are available

var iterator = arrayIterator([1, 2, 3]);
iterator(); // { value: 1, index: 0 }
iterator(); // { value: 2, index: 1 }
iterator(); // { value: 3, index: 2 }
iterator(); // undefined
pfraces commented 8 years ago
var arrayIterator = function (array) {
  var length = array.length;
  var index = 0;

  var iterator = function () {
    if (index === length) { return; }
    var iteration = { value: array[index], index: index };
    index = index + 1;
  };

  return iterator;
};
pfraces commented 8 years ago
var each = function (iteratee, iterator) {
  var iteration = null;

  while (iteration = iterator()) {
    iteratee(iteration.value, iteration.index);
  }
};
pfraces commented 8 years ago

Async variant

var iterator = arrayIterator([1, 2, 3]);

iterator(function (value, index) {
  // ...
});

With this variant it makes no sense to implement an each method for iterators since the iterator itself is enough

It supports both, sync and async variants and the standard array/object iterators can get an additional parameters like async: true or the number of iterations in a tick...