Delegated yield (yield star, yield *) in generator functions

后端 未结 3 769

ECMAScript 6 should be bringing generator functions and iterators. A generator function (which has the function* syntax) returns an iterator. The iterator has a

3条回答
  •  轮回少年
    2020-11-27 06:03

    Delegating to another generator means the current generator stops producing values by itself, instead yielding the values produced by another generator until it exhausts it. It then resumes producing its own values, if any.

    For instance, if secondGenerator() produces numbers from 10 to 15, and firstGenerator() produces numbers from 1 to 5 but delegates to secondGenerator() after producing 2, then the values produced by firstGenerator() will be:

    1, 2, 10, 11, 12, 13, 14, 15, 3, 4, 5
    

    function* firstGenerator() {
        yield 1;
        yield 2;
        // Delegate to second generator
        yield* secondGenerator();
        yield 3;
        yield 4;
        yield 5;
    }
    
    function* secondGenerator() {
        yield 10;
        yield 11;
        yield 12;
        yield 13;
        yield 14;
        yield 15;
    }
    
    console.log(Array.from(firstGenerator()));

提交回复
热议问题