How to get the nth value of a JavaScript generator?

前端 未结 4 1436
萌比男神i
萌比男神i 2020-12-19 18:07

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.         


        
4条回答
  •  無奈伤痛
    2020-12-19 18:36

    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.

提交回复
热议问题