Joshua Engel
Joshua Engel

Reputation: 503

Is yield* equivalent to a while loop with plain yield in javascript?

If I have a line like:

yield* foo()

Could I replace it with something to the tune of:

while(true) {
   var x = foo.next();
   if(x.done)
       break;
    yield x;
}

Clearly that's more verbose, but I'm trying to understand if yield* is merely syntactic sugar, or if there's some semantic aspect I'm unclear on.

Upvotes: 5

Views: 2634

Answers (1)

Rodrigo5244
Rodrigo5244

Reputation: 5525

Instead of yield x you need to do yield x.value. You also need to call foo to get the iterator. .next is a method of the iterator returned by the foo generator.

function *foo() {
  yield 1;
  yield 2;
  yield 3;
}

function *f() {
  yield *foo();
}

console.log(Array.from(f()));

function *g() {
  var iterator = foo();
  while (true) {
    var x = iterator.next();
    if (x.done) break;
    yield x.value;
  }
}

console.log(Array.from(g()));

Upvotes: 1

Related Questions