Emulating generators in Javascript with closures

I’ve just had a silly realization regarding Javascript, since closures maintain state it is possible to use them to emulate other languages’ generators (or even the Javascript ones in upcoming versions).

It works like a factory function in which the returned f modifies the context in which it was created, here’s a generator of integers:

Fibonacci:

So… what do we use this for? isn’t it the same as looping on your own? fair enough, this is one of those things that seem useless until you start using them, then they suddenly “click” and you think “how could I’ve lived without them??”

Or maybe they are useless but you just start to like them for no reason, anyway what I think this is useful for is to separate the looping part from the code that works with the looped results, think about Newton’s square root method:

This can be expressed using a generator for the guess which separates the algorithm from the approximation:

One last example, emulating Python’s range statement as an iterator (xrange):

Here’s some info on the latest spec for this feature (v1.7/1.8): https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators

rhysbrettbowen from reddit tels us about this library: stream.js which formally embraces the concept presented here, try it out!