4

In C# I can call method .ToList() to get all results from a iterable function, like this:

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 = ???;
MuriloKunze
  • 14,315
  • 17
  • 50
  • 81

4 Answers4

4

Apparently this works:

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

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

I came up with this by fiddling around with this example on MDN.

For information about the spread operator (...), have a look at this documentation on MDN. Be aware of its current limited browser support, though.

Decent Dabbler
  • 21,869
  • 8
  • 72
  • 103
3

An alternative to the spread operator would be just to use Array.from which takes any iterable source and creates an array from it:

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}
var result = Array.from(gen());
CodingIntrigue
  • 71,301
  • 29
  • 165
  • 172
1

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 for loop

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 for..of loop

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

var results = [];

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

console.log(results)
guest271314
  • 1
  • 12
  • 91
  • 170
0

A helper 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());
freakish
  • 51,131
  • 8
  • 123
  • 162