Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set the result of a generator function in a variable [duplicate]

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 = ???;
like image 630
MuriloKunze Avatar asked Feb 08 '23 15:02

MuriloKunze


2 Answers

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.

like image 85
Decent Dabbler Avatar answered Feb 11 '23 00:02

Decent Dabbler


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());
like image 28
CodingIntrigue Avatar answered Feb 11 '23 01:02

CodingIntrigue