如何获得JavaScript生成器的第n个值? [英] How to get the nth value of a JavaScript generator?

查看:104
本文介绍了如何获得JavaScript生成器的第n个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取发电机的第n个值?

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


推荐答案

您可以定义枚举方法,如< python中的href =https://docs.python.org/3/library/functions.html#enumerate =nofollow:

You can define an enumeration method like in python:

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

然后:

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

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

同样的,也可以重新实现pythonic range islice

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;
    }
  }
}

然后:

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.

这篇关于如何获得JavaScript生成器的第n个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆