bebraw
3/23/2012 - 12:04 PM

Generators in JavaScript

Generators in JavaScript

function generator(valueCb) {
  return function() {
    var i = 0;

    return {
      next: function() {
        var ret = valueCb(i);
        i++;
        
        return ret;
      }
    };
  }();
}

function cycle() {
  var items = arguments;
  
  return generator(function(i) {
    return items[i % items.length];
  });
}

function pows(n) {
  return generator(function(i) {
    return Math.pow(i, n);
  });
}

// example of a cycle
var color = cycle('red', 'green', 'blue');
// color.next() -> red, green, blue, red, green, ...

// pow examples
var nums = pows(1); // 0, 1, 2, 3, ...
var squares = pows(2); // 0, 1, 2, 4, 9, ...
var cubes = pows(3); // 0, 1, 8, 27, 64, ...