0

I find this example and I was surprising the way that the eventually values of the generator are get from the generator. This is the code:

function* foo() {
  yield 'a';
  yield 'b';
  yield 'c';
}

const [...values] = foo();

Based on my understand of generators, i think that destructuring a generator execution is equivalent to:

const array = [];
for(const val of foo()) {
    array.push(val)
}

so, my question is: It is this a valid approach to get the values of a generator function and what other ways exists for achieve this?

  • That seems a'ight to me – James Kraus May 16 '17 at 17:44
  • 2
    "is this a valid approach?" -- [does it work? Yes? Then it's valid.](https://esfiddle.net/j2ruoocs/) "what other ways exist to achieve this?" Lots; likely that bit is too broad a question for SO. – Heretic Monkey May 16 '17 at 17:47
  • 1
    It is valid, but IMHO less readable than `const values = [...foo()]` or even `const values = Array.from(foo())`. – le_m May 16 '17 at 18:01
  • Related/duplicate: [Creating an array from ES6 generator](http://stackoverflow.com/q/43939821/218196) – Felix Kling May 16 '17 at 19:34

1 Answers1

7

The iteration (iterable & iterator) protocols offer you an ocean of possibilities...

function* foo() {
  yield 'a';
  yield 'b';
  yield 'c';
}

const [...values] = foo();

console.log(...values);

function* foo() {
  yield 'a';
  yield 'b';
  yield 'c';
}

const [a, b, c] = foo();

console.log(a, b, c);

function* foo() {
  yield 'a';
  yield 'b';
  yield 'c';
};

let values = [];

for (const str of foo()) {
  values.push(str);
}

console.log(values[0], values[1], values[2]);

function* foo() {
  yield 'a';
  yield 'b';
  yield 'c';
}

const [a, b, ...values] = Array.from(foo());

console.log(a, b, values.toString());

let foo = (function* () {
  yield 'a';
  yield 'b';
  yield 'c';
})();

console.log(foo.next().value, foo.next().value, foo.next().value);
Badacadabra
  • 8,043
  • 7
  • 28
  • 49