serge
serge

Reputation: 15229

use yield inside another yield

I would like to use generator to print the content of an array, however yield inside another yield is confusing to me

let myArray = ["a", "b", "c"]

function* line(array){
  yield "my array"
  array.forEach(function*(v){yield v})
}

console.log(Array.from(line(myArray)))

is there a way to print the "a", "b" and "c" each in a new line with the code above?

expected output

my array
a
b
c

Upvotes: 0

Views: 201

Answers (2)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

Sure, it's yield*

let myArray = ["a", "b", "c"]

function* line(array){
  yield "my array"
  yield* array
}

console.log(Array.from(line(myArray)))

Upvotes: 1

Dai
Dai

Reputation: 155055

Being explicit, with a visible inner for(of):

let myArray = ["a", "b", "c"]

function* line(array) {
  yield "my array";

  for( const ch of array ) {
    yield ch;
  }
}

console.log(Array.from(line(myArray)))

Using implicit iteration with yield*:

let myArray = ["a", "b", "c"]

function* line(array) {
  yield "my array";
  yield* array;
}

console.log(Array.from(line(myArray)))

...basically, yield* $iterable; is the same thing as doing for( const v of $iterable ) yield v;.

Upvotes: 1

Related Questions