polkovnikov.ph polkovnikov.ph - 6 months ago 44
Javascript Question

How to clone ES6 generator?

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)


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.

Answer

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.

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?