Set the result of the generator function in a variable

In C #, I can call a method .ToList()to get all the results from an iterative function, for example:

var results = IterableFunction().ToList();

Following the code below, how can I set the result in a variable?

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}

var results = ???;
+4
source share
4 answers

This seems to work:

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}

var results = [...gen()];

I came up with this by taking this example to MDN .

For information on the distribution operator ( ...), see this documentation in MDN . Remember the current limited browser , however.

+4
source

Array.from, :

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}
var result = Array.from(gen());
+3

Step by step

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}

var g = gen();
var results = [];
results.push(g.next().value);
results.push(g.next().value);
results.push(g.next().value);
console.log(results);

Alternatively using a loop for

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}

var results = [];

for (var g = gen(), curr = g.next(); !curr.done
  ; results.push(curr.value), curr = g.next());

console.log(results);

another approach would be to use a loop for..of

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}

var results = [];

for (let prop of gen()) {
  results.push(prop)
}

console.log(results)
+1
source

Auxiliary function:

function generator_to_list(generator) {
    var result = [];
    var next = generator.next();
    while (!next.done) {
        result.push(next.value);
        next = generator.next();
    }
    return result;
}

and then your code:

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}
var result = generator_to_list(gen());
0
source

All Articles