This repo contains the code for the chapter Generators, advanced iteration and others
Read the chapter Generators, advanced iteration of JavaScript.info reproducing the examples and exercises.
Additionally:
- Study and solve the exercise Groups in the book EloquentJS Chapter 6
- Study an solve the Iterable groups extension of the exercise Groups in EloquentJS Chapter 6 making the
Groupclass from the previous exercise iterable - Simplify the solution to making the
Groupclass iterable using a generator instead of a plain iterator as suggested in Chapter 11 of the book Eloquent JS
Generators are created by generator functions
function* f( ... ) {
...
}Only inside generators you can use the yield operator.
The caller code and the generator may exchange results via next/yield calls.
Generators are great for making iterable objects.
Async generators are used to read streams of asynchronously generated data (e.g paginated fetches over a network) in for await ... of loops.
The next() method returns an object with two properties done and value. You can also provide a parameter to the next method to send a value to the generator.
The throw() method resumes the execution of a generator by throwing an error into it and returns an object with two properties done and value.