Please support this book: buy it or donate

(Ad, please don’t block.)

35 Synchronous generators (advanced)

35.1 What are synchronous generators?

Synchronous generators are special versions of function definitions and method definitions that always return synchronous iterables:

// Generator function declaration function * genFunc1() { /*···*/ } genFunc1() { // Generator function expression const genFunc2 = function * () { /*···*/ } ; genFunc2() { // Generator method definition in an object literal const obj = { obj * generatorMethod() { generatorMethod() { // ··· } } ; // Generator method definition in a class definition // (class declaration or class expression) class MyClass { MyClass { * generatorMethod() { generatorMethod() { // ··· } }

Asterisks ( * ) mark functions and methods as generators:

Functions: The pseudo-keyword function* is a combination of the keyword function and an asterisk.

is a combination of the keyword and an asterisk. Methods: The * is a modifier (similar to static and get ).

35.1.1 Generator functions return iterables and fill them via yield

If you call a generator function, it returns an iterable (actually, an iterator that is also iterable). The generator fills that iterable via the yield operator:

function * genFunc1() { genFunc1() { yield 'a' ; yield 'b' ; } const iterable = genFunc1() ; iterablegenFunc1() // Convert the iterable to an Array, to check what’s inside: . deepEqual ([ ... iterable ] , [ 'a' , 'b' ]) ; assert([]) // You can also use a for-of loop for ( const x of genFunc1()) { genFunc1()) { console . log (x) ; (x) } // Output: // 'a' // 'b'

35.1.2 yield pauses a generator function

Using a generator function involves the following steps:

Function-calling it returns an iterator iter (that is also an iterable).

(that is also an iterable). Iterating over iter repeatedly invokes iter.next() . Each time, we jump into the body of the generator function until there is a yield that returns a value.

Therefore, yield does more than just add values to iterables – it also pauses and exits the generator function:

Like return , a yield exits the body of the function and returns a value (via .next() ).

, a exits the body of the function and returns a value (via ). Unlike return , if you repeat the invocation (of .next() ), execution resumes directly after the yield .

Let’s examine what that means via the following generator function.

let location = 0 ; location function * genFunc2() { genFunc2() { = 1 ; yield 'a' ; location = 2 ; yield 'b' ; location = 3 ; location }

In order to use genFunc2() , we must first create the iterator/iterable iter . genFunc2() is now paused “before” its body.

const iter = genFunc2() ; itergenFunc2() // genFunc2() is now paused “before” its body: . equal (location , 0 ) ; assert(location

iter implements the iteration protocol. Therefore, we control the execution of genFunc2() via iter.next() . Calling that method resumes the paused genFunc2() and executes it until there is a yield . Then execution pauses and .next() returns the operand of the yield :

. deepEqual ( assert . next () , { value : 'a' , done : false }) ; iter()}) // genFunc2() is now paused directly after the first `yield`: . equal (location , 1 ) ; assert(location

Note that the yielded value 'a' is wrapped in an object, which is how iterators always deliver their values.

We call iter.next() again and execution continues where we previously paused. Once we encounter the second yield , genFunc2() is paused and .next() returns the yielded value 'b' .

. deepEqual ( assert . next () , { value : 'b' , done : false }) ; iter()}) // genFunc2() is now paused directly after the second `yield`: . equal (location , 2 ) ; assert(location

We call iter.next() one more time and execution continues until it leaves the body of genFunc2() :

. deepEqual ( assert . next () , { value : undefined , done : true }) ; iter()}) // We have reached the end of genFunc2(): . equal (location , 3 ) ; assert(location

This time, property .done of the result of .next() is true , which means that the iterator is finished.

35.1.3 Why does yield pause execution?

What are the benefits of yield pausing execution? Why doesn’t it simply work like the Array method .push() and fill the iterable with values without pausing?

Due to pausing, generators provide many of the features of coroutines (think processes that are multitasked cooperatively). For example, when you ask for the next value of an iterable, that value is computed lazily (on demand). The following two generator functions demonstrate what that means.

/** * Returns an iterable over lines */ function * genLines() { genLines() { yield 'A line' ; yield 'Another line' ; yield 'Last line' ; } /** * Input: iterable over lines * Output: iterable over numbered lines */ function * numberLines(lineIterable) { numberLines(lineIterable) { let lineNumber = 1 ; lineNumber for ( const line of lineIterable) { // input linelineIterable) { yield lineNumber + ': ' + line ; // output lineNumberline ++; lineNumber } }

Note that the yield in numberLines() appears inside a for-of loop. yield can be used inside loops, but not inside callbacks (more on that later).

Let’s combine both generators to produce the iterable numberedLines :

const numberedLines = numberLines(genLines()) ; numberedLinesnumberLines(genLines()) . deepEqual ( assert . next () , { value : '1: A line' , done : false }) ; numberedLines()}) . deepEqual ( assert . next () , { value : '2: Another line' , done : false }) ; numberedLines()})

The key benefit of using generators here is that everything works incrementally: via numberedLines.next() , we ask numberLines() for only a single numbered line. In turn, it asks genLines() for only a single unnumbered line.

This incrementalism continues to work if, for example, genLines() reads its lines from a large text file: If we ask numberLines() for a numbered line, we get one as soon as genLines() has read its first line from the text file.

Without generators, genLines() would first read all lines and return them. Then numberLines() would number all lines and return them. We therefore have to wait much longer until we get the first numbered line.

Exercise: Turning a normal function into a generator exercises/sync-generators/fib_seq_test.mjs

35.1.4 Example: Mapping over iterables

The following function mapIter() is similar to the Array method .map() , but it returns an iterable, not an Array, and produces its results on demand.

function * mapIter(iterable , func) { mapIter(iterablefunc) { let index = 0 ; index for ( const x of iterable) { iterable) { yield func(x , index) ; func(xindex) ++; index } } const iterable = mapIter([ 'a' , 'b' ] , x => x + x) ; iterablemapIter([x) . deepEqual ([ ... iterable ] , [ 'aa' , 'bb' ]) ; assert([])

Exercise: Filtering iterables exercises/sync-generators/filter_iter_gen_test.mjs

35.2 Calling generators from generators (advanced)

35.2.1 Calling generators via yield*

yield only works directly inside generators – so far we haven’t seen a way of delegating yielding to another function or method.

Let’s first examine what does not work: in the following example, we’d like foo() to call bar() , so that the latter yields two values for the former. Alas, a naive approach fails:

function * bar() { bar() { yield 'a' ; yield 'b' ; } function * foo() { foo() { // Nothing happens if we call `bar()`: ; bar() } . deepEqual ( assert [ ... foo ()] , []) ; ()][])

Why doesn’t this work? The function call bar() returns an iterable, which we ignore.

What we want is for foo() to yield everything that is yielded by bar() . That’s what the yield* operator does:

function * bar() { bar() { yield 'a' ; yield 'b' ; } function * foo() { foo() { yield * bar() ; bar() } . deepEqual ( assert [ ... foo ()] , [ 'a' , 'b' ]) ; ()]])

In other words, the previous foo() is roughly equivalent to:

function * foo() { foo() { for ( const x of bar()) { bar()) { yield x ; } }

Note that yield* works with any iterable:

function * gen() { gen() { yield * [ 1 , 2 ] ; } . deepEqual ( assert [ ... gen ()] , [ 1 , 2 ]) ; ()]])

35.2.2 Example: Iterating over a tree

yield* lets us make recursive calls in generators, which is useful when iterating over recursive data structures such as trees. Take, for example, the following data structure for binary trees.

class BinaryTree { BinaryTree { , left = null , right = null ) { constructor(valueleftright) { this . value = value ; value this . left = left ; left this . right = right ; right } /** Prefix iteration: parent before children */ * [ Symbol . iterator ]() { ]() { yield this . value ; if ( this . left ) { ) { // Same as yield* this.left[Symbol.iterator]() yield * this . left ; } if ( this . right ) { ) { yield * this . right ; } } }

Method [Symbol.iterator]() adds support for the iteration protocol, which means that we can use a for-of loop to iterate over an instance of BinaryTree :

const tree = new BinaryTree( 'a' , treeBinaryTree( new BinaryTree( 'b' , BinaryTree( new BinaryTree( 'c' ) , BinaryTree( new BinaryTree( 'd' )) , BinaryTree()) new BinaryTree( 'e' )) ; BinaryTree()) for ( const x of tree) { tree) { console . log (x) ; (x) } // Output: // 'a' // 'b' // 'c' // 'd' // 'e'

Exercise: Iterating over a nested Array exercises/sync-generators/iter_nested_arrays_test.mjs

35.3 Background: external iteration vs. internal iteration

In preparation for the next section, we need to learn about two different styles of iterating over the values “inside” an object:

External iteration (pull): Your code asks the object for the values via an iteration protocol. For example, the for-of loop is based on JavaScript’s iteration protocol: for ( const x of [ 'a' , 'b' ]) { ]) { console . log (x) ; (x) } // Output: // 'a' // 'b'

Internal iteration (push): You pass a callback function to a method of the object and the method feeds the values to the callback. For example, Arrays have the method .forEach() : [ 'a' , 'b' ] . forEach ((x) => { ((x) console . log (x) ; (x) ; }) // Output: // 'a' // 'b'

The next section has examples for both styles of iteration.

35.4 Use case for generators: reusing traversals

One important use case for generators is extracting and reusing traversals.

35.4.1 The traversal to reuse

As an example, consider the following function that traverses a tree of files and logs their paths (it uses the Node.js API for doing so):

function logPaths (dir) { (dir) { for ( const fileName of fs . readdirSync (dir)) { fileNamefs(dir)) { const filePath = path . resolve (dir , fileName) ; filePathpath(dirfileName) console . log (filePath) ; (filePath) const stats = fs . statSync (filePath) ; statsfs(filePath) if (stats . isDirectory ()) { (stats()) { ; // recursive call logPaths(filePath) } } }

Consider the following directory:

mydir/ a.txt b.txt subdir/ c.txt

Let’s log the paths inside mydir/ :

How can we reuse this traversal and do something other than logging the paths?

35.4.2 Internal iteration (push)

One way of reusing traversal code is via internal iteration: Each traversed value is passsed to a callback (line A).

function visitPaths (dir , callback) { (dircallback) { for ( const fileName of fs . readdirSync (dir)) { fileNamefs(dir)) { const filePath = path . resolve (dir , fileName) ; filePathpath(dirfileName) ; // (A) callback(filePath) const stats = fs . statSync (filePath) ; statsfs(filePath) if (stats . isDirectory ()) { (stats()) { , callback) ; visitPaths(filePathcallback) } } } const paths = [] ; paths[] 'mydir' , p => paths . push (p)) ; visitPaths(paths(p)) . deepEqual ( assert , paths [ 'mydir/a.txt' , 'mydir/b.txt' , 'mydir/subdir' , 'mydir/subdir/c.txt' , ; ])

35.4.3 External iteration (pull)

Another way of reusing traversal code is via external iteration: We can write a generator that yields all traversed values (line A).

function * iterPaths(dir) { iterPaths(dir) { for ( const fileName of fs . readdirSync (dir)) { fileNamefs(dir)) { const filePath = path . resolve (dir , fileName) ; filePathpath(dirfileName) yield filePath ; // (A) filePath const stats = fs . statSync (filePath) ; statsfs(filePath) if (stats . isDirectory ()) { (stats()) { yield * iterPaths(filePath) ; iterPaths(filePath) } } } const paths = [ ... iterPaths ( 'mydir' )] ; paths)]

35.5 Advanced features of generators

The chapter on generators in Exploring ES6 covers two features that are beyond the scope of this book: