joker
joker

Reputation: 11

Why only once next function running in generators recursion?

In my think. I have to run next function in many times,by below code.

code environment:Google Chrome browser. version: 63.0.3239.132.

const a = [1,2,3,[4,5],6,[7,8]];

function *fun(array){
    for(let i = 0;i<array.length;i++){
        if(Array.isArray(array[i])){
            yield *fun(array[i]);
        }
    }
}

console.log(fun(a).next().done);//true

In usually generators function,just one yield.It have to run twice next function then done become true.

For Example:

function *foo() {
    yield 1;
}

const iterator = foo();
console.log(iterator.next().done);//false
console.log(iterator.next().done);//true

Why in the recursion Example,it just run once then iterator had done?

By the way, this doubt from the book which name is You-Dont-Know-JS in chapter 3.

Upvotes: 1

Views: 72

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

You are missing the yield statement for the items that are not arrays:

const a = [1,2,3,[4,5],6,[7,8]];

function *fun(array){
    for(let i = 0;i<array.length;i++){
        if(Array.isArray(array[i])){
            yield *fun(array[i]);
        } else { // if the item is not an array
            yield array[i];
        }
    }
}

const f = fun(a);

console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());

Upvotes: 2

Related Questions