Andrew's Blfog

Javascript generator functions

It has been a while since my last blog post!

I learned recently about generator functions, having successfully avoided them for over a decade. The basic idea in Javascript is that they are a function that returns a special iterable object. Iterable in this case meaning you can loop over it.


function* generatorFunctionOne () {
    yield "a";
    yield "b";
    yield "c";
    yield "d";
}

const g = generatorFunctionOne();

for (const yieldedItem of g) {
    console.log(yieldedItem);
}

/* 
 * Logs, in order:
 * - a
 * - b
 * - c
 * - d
*/

That's a rather contrived example, but more-or-less shows the base concept - each next call (or each iteration) will continue up to the next yield, and whatever that yield is will be provided as the iterable element, and can be repeated ad nauseum via a loop. So, for example, if you wanted to generate n random numbers...

Read More...