Javascript generators

From wikinotes

Generator functions allow you to change context and return without losing context.
You can use this to create infinite loops, factories, etc. Similar to python generators.

Documentation

generator functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

Basics

function* counter(count = 0) {
    while (true) {
        yield count++
    }
}

count = counter(10)
count.next()        // { value: 11, done: false }
count.next().value  // 12
count.next().value  // 13
// ...

Generators yield an object with a .value property.
You can exit early

Generator Methods

class Sheep {
    *count () { ... }
}

Methods can also be generators

Yield from another Generator

yield* other_generator will yield the result from another generator as your result.