Is it possible to reset an ECMAScript 6 generator to its initial state?

前端 未结 8 1380
有刺的猬
有刺的猬 2020-12-01 12:19

Given the provided (very simple) generator, is it possible to return the generator back to its original state to use again?

var generator = function*() {
            


        
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 12:23

    Whenever you need to "reset" an iterable, just toss the old one away and make a new one.

    var generator = function*() {
        yield 1;
        yield 2;
        yield 3;
    };
    const makeIterable = () => generator()
    
    for (let x of makeIterable()) {
        console.log(x);
    }
    
    // At this point, iterable is consumed.
    // Is there a method for moving iterable back
    // to the start point by only without re-calling generator(),
    // (or possibly by re-calling generator(), only by using prototype 
    //  or constructor methods available within the iterable object)
    // so the following code would work again?
    
    for (let x of makeIterable()) {
        console.log(x);
    }

提交回复
热议问题