How can I get the nth value of a generator?
function *index() {
let x = 0;
while(true)
yield x++;
}
// the 1st value
let a = index();
console.log(a.
You could create an array of size n, and use Array.from and its second argument to fetch the values you need. So assuming iter is the iterator from generator gen:
var iter = gen();
Then the first n values can be fetched as follows:
var values = Array.from(Array(n), iter.next, iter).map(o => o.value)
...and when you are only interested in the nth value, you could skip the map part, and do:
var value = Array.from(Array(n), iter.next, iter).pop().value
Or:
var value = [...Array(n)].reduce(iter.next.bind(iter), 1).value
The downside is that you still (temporarily) allocate an array of size n.