如何克隆ES6发电机? [英] How to clone ES6 generator?

查看:127
本文介绍了如何克隆ES6发电机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用生成器在ES6中创建一个列表 monad。为了使其工作,我需要创建已经消耗了几个状态的迭代器的副本。如何克隆ES6中的迭代器?

I'm trying to create a List monad in ES6 using generators. To make it work I need to create a copy of an iterator that has already consumed several states. How do I clone an iterator in ES6?

function* test() {
    yield 1;
    yield 2;
    yield 3;
}

var x = test();
console.log(x.next().value); // 1
var y = clone(x);
console.log(x.next().value); // 2
console.log(y.next().value); // 2 (sic)

我尝试过克隆 cloneDeep lodash ,但它们没有用。以这种方式返回的迭代器是本机函数并在内部保持状态,所以似乎没有办法使用自己的JS代码。

I've tried clone and cloneDeep from lodash, but they were of no use. Iterators that are returned in this way are native functions and keep their state internally, so it seems there's no way to do it with own JS code.

推荐答案


迭代器[...]保持内部状态,所以似乎没有办法

Iterators […] keep their state internally, so it seems there's no way

是的,这是一个很好的理由。您不能克隆状态,否则您可能会使用发生器篡改太多。

Yes, and that for a good reason. You cannot clone the state, or otherwise you could tamper too much with the generator.

然而,可能会创建一个运行的第二个迭代器, em>第一个,通过记住它的序列,并再次产生它。但是,应该只有一个真正的驱动器的迭代器,否则,你的克隆中的哪一个被允许发送 next()参数?

It might be possible however to create a second iterator that runs alongside of the first one, by memorizing its sequence and yielding it later again. However, there should be only one iterator that really drives the generator - otherwise, which of your clones would be allowed to send next() arguments?

这篇关于如何克隆ES6发电机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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