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 = ???;
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With