Skip to content

Instantly share code, notes, and snippets.

@bebraw
Created March 23, 2012 12:04
Show Gist options
  • Save bebraw/2170059 to your computer and use it in GitHub Desktop.
Save bebraw/2170059 to your computer and use it in GitHub Desktop.
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, ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment