Search code examples
javascriptecmascript-6es6-generator

Is there a way to reduce the number of yields in an infinite generator communicating with its caller?


At a discussion about Javascript generators someone cooked up an interesting function:

function *foo() {
    var y = 1;
    while(true) yield (y = (y * (yield)));
}

Now, this function can be used via:

var results = [];
var bar = foo();
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));
bar.next();
results.push(bar.next(2));

As we can see, in order to get the next product we need to call next twice. The question is: can this somehow be resolved with a single yield?


Solution

  •   while(true) y *=  yield y;
    

    Just yield y and then multiply y with its result.

    function *foo() {
        let y = 1;
        while(true) y *=  yield y;
    }
    
    const bar = foo();
    bar.next();
    console.log(bar.next(2).value);
    console.log(bar.next(2).value);
    console.log(bar.next(2).value);