Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  42] [ 6]  / answers: 1 / hits: 20399  / 8 Years ago, thu, august 11, 2016, 12:00:00

I want to create an array from the values of an generator in JavaScript.
The generator creates a sequence of dynamic length like this



function* sequenceGenerator(minVal, maxVal) {
let currVal = minVal;

while(currVal < maxVal)
yield currVal++;
}


I want to store those values in an array but using next() until the generator is done does not seem to be the best way possible (and looks quite ugly to be honest).



var it, curr, arr;

it = sequenceGenerator(100, 1000);
curr = it.next();
arr = [];

while(! curr.done){
arr.push(curr.value);
}


Can I somehow create an array directly from/within the generator?
If not, can I somehow avoid/hide the loop? Maybe by using map or something like that?



Thanks in advance.


More From » arrays

 Answers
1

I found another way



var arr = Array.from( sequenceGenerator(min, max) );


works aswell.


[#61065] Tuesday, August 9, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
americar

Total Points: 631
Total Questions: 107
Total Answers: 103

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;