1

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.

4
  • Why did you put ; after } from the if clause? Commented Jan 19, 2018 at 8:01
  • My be It is my code habit?It right or mistake? Commented Jan 19, 2018 at 8:13
  • It is a mistake. Commented Jan 19, 2018 at 8:16
  • In your code, there is nothing to yield when a value is not an array. When your iterate over your first array and found an array as item, you delegate to a new generator (the same but on the array value). yield *fun means you delegate to a new iterator. What behaviour are you waiting for ? Commented Jan 19, 2018 at 9:00

1 Answer 1

2

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());

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.