Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my array
a
b
c

>Solution :

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;.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading