Created
September 25, 2012 22:11
-
-
Save mattbierner/3784785 to your computer and use it in GitHub Desktop.
Gen.js Example
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
// Source generator for fibonacci sequence | |
function fibonacci() { | |
var c = 0, d = 1; | |
return function(y, b) { | |
var next = c; | |
c = d; | |
d = next + d; | |
return y(next); | |
}; | |
} | |
var f = gen(fibonacci()) | |
.sync(); | |
f(); -> 0 | |
f(); -> 1 | |
f(); -> 1 | |
f(); -> 2 | |
f(); -> 3 | |
f(); -> 5 | |
... | |
// Operations can also be applied to generators: | |
// Square each Fibonacci number. | |
var f = gen(fibonacci()) | |
.map(function(v){ return v * v;}) | |
.sync(); | |
f(); -> 0 | |
f(); -> 1 | |
f(); -> 1 | |
f(); -> 4 | |
f(); -> 9 | |
f(); -> 25 | |
.... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment