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?

4
  • That seems a'ight to me Commented May 16, 2017 at 17:44
  • 2
    "is this a valid approach?" -- does it work? Yes? Then it's valid. "what other ways exist to achieve this?" Lots; likely that bit is too broad a question for SO. Commented May 16, 2017 at 17:47
  • 1
    It is valid, but IMHO less readable than const values = [...foo()] or even const values = Array.from(foo()). Commented May 16, 2017 at 18:01
  • Related/duplicate: Creating an array from ES6 generator Commented May 16, 2017 at 19:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.