How to get the nth value of a JavaScript generator?

前端 未结 4 1445
萌比男神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:24

    You can define an enumeration method like in python:

    function *enumerate(it, start) {
       start = start || 0;
       for(let x of it)
         yield [start++, x];
    }
    

    and then:

    for(let [n, x] of enumerate(index()))
      if(n == 6) {
        console.log(x);
        break;
      }
    

    http://www.es6fiddle.net/ia0rkxut/

    Along the same lines, one can also reimplement pythonic range and islice:

    function *range(start, stop, step) {
      while(start < stop) {
        yield start;
        start += step;
      }
    }
    
    function *islice(it, start, stop, step) {
      let r = range(start || 0, stop || Number.MAX_SAFE_INTEGER, step || 1);
      let i = r.next().value;
      for(var [n, x] of enumerate(it)) {
        if(n === i) {
          yield x;
          i = r.next().value;
        }
      }
    }
    

    and then:

    console.log(islice(index(), 6, 7).next().value);
    

    http://www.es6fiddle.net/ia0s6amd/

    A real-world implementation would require a bit more work, but you got the idea.

提交回复
热议问题