Created
March 23, 2012 12:04
-
-
Save bebraw/2170059 to your computer and use it in GitHub Desktop.
Generators in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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