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
  • 15,195
  • 17
  • 54
  • 82

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
  • 22,532
  • 8
  • 74
  • 106
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
  • 75,930
  • 30
  • 170
  • 176
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
  • 15
  • 104
  • 177
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
  • 54,167
  • 9
  • 132
  • 169