bresson
bresson

Reputation: 901

Confused by the generator

In the code below (taken from Javascript Concurrency), there should be three generator objects after the iterable = genMap(iterable, iteratee) for-of loop. However, yield* iterable is a single reference. How does it yield three sets of values from genMap? Thank you.

function* genMap(iterable, iteratee) {
    for (let item of iterable) {
        console.log('item', item)
        yield iteratee(item);
    }
}

function composeGenMap(...iteratees) {

    return function* (iterable) {
        for (let iteratee of iteratees) {
            iterable = genMap(iterable, iteratee);
        }

        yield* iterable; 
    }
}

// Our iterable data source.
var array = [ 1, 2, 3 ];

var composed = composeGenMap(
    x => x + 1,
    x => x * x,
    x => x - 2
);

for (let item of composed(array)) {
    console.log('composed', item)
}
// →
// composed 2
// composed 7
// composed 14

Upvotes: 0

Views: 76

Answers (1)

gyre
gyre

Reputation: 16779

yield* defers execution to another generator, or perhaps an iterable if you so desire.

That means it can technically yield more than one value (three in your case).

From the Mozilla Developer Network article on yield*:

The yield* expression is used to delegate to another generator or iterable object.

Upvotes: 1

Related Questions