I have started a little project that tries to do this with some callback trickery. Since it's impossible to create real coroutines in "standard" JavaScript, this doesn't come without a few caveats, e.g:
- it's impossible to make this follow the iterator protocol (stuff like
.next()
etc.),
- it's impossible to iterate through several generators at once,
- you have to watch out not to let the wrong objects leave the generator's scope (e.g. by calling
yield
in a timeout – since this is "plain" JavaScript, there's no syntax restriction that prevents you from doing this),
- exceptions in the generator are a little tricky,
- and last not least, it's very experimental (just started this a few days ago).
On the bright side, you have yield
! :)
The Fibonacci example from the MDC page would look like this:
var fibonacci = Generator(function () {
var fn1 = 1;
var fn2 = 1;
while (1){
var current = fn2;
fn2 = fn1;
fn1 = fn1 + current;
this.yield(current);
}
});
console.log(fibonacci.take(10).toArray());
Output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
The project is on BitBucket at https://bitbucket.org/balpha/lyfe.