JavaScript Generators: Building Lazy and Infinite Sequences
Generators pause and resume, which makes them perfect for lazy evaluation. Here is how I use them for pipelines and state machines. A generator is a function that can pause execution and yield values one at a time, resuming later when the next value is requested. This turns a function into a pull-based stream, which is the natural model for lazy and infinite sequences. Once I started thinking in generators, I found I could express pipelines that process data as it arrives without buffering entire collections in memory. The Basics of Yield A generator function is declared with function* and uses yield to emit values. Calling a generator function does not run its body; it returns a generator object, which is both an iterator and an iterable. Each call to next() runs the body until the next yield, returns the yielded value, and pauses. When the function returns, the generator is done. function* naturals() { let n = 1; while (true) yield n++; } const gen = naturals(); gen.next(); // { value: 1, done: false } gen.next(); // { value: 2, done: false } Because the generator only computes the next value…