Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 870
Joshua Engel Avatar asked Nov 09 '22 03:11

Joshua Engel


1 Answers

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()));
like image 89
Rodrigo5244 Avatar answered Nov 14 '22 23:11

Rodrigo5244