Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the nth value of a JavaScript generator?

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.next().value); // 0

// the 3rd value
let b = index();
b.next();
b.next();
console.log(b.next().value); // 2

// the nth value?
let c = index();
let n = 10;
console.log(...); // 9
like image 604
Mulan Avatar asked May 23 '15 07:05

Mulan


1 Answers

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.

like image 120
georg Avatar answered Oct 03 '22 08:10

georg