Special generators whose iterators can be cloned.
import recorder from './recorder-generator.js'
const decoratedGenerator = recorder(generatorFunction)
// The decorated generator has the same surface API and the same source
const iterator1 = decoratedGenerator(generatorInput)
while(condition1){
// The iterator produced behaves as normal
iterator1.next(Date.now())
}
// Fork creates a new initialisation of the decorated generator
// then fast-forwards it to the same state as iterator2
const iterator2 = iterator1.fork()
// The 2 iterators can now diverge
The iterator isn't really cloned – instead all input provided its yield
evaluations are recorded; When the .fork()
method is invoked, the source generator is re-run with the same input, then the resulting iterator is advanced, using .next()
, and fed the same memoized input in the same sequence as the base.
The author should take care only to record and fork generators without side-effects, or a .fork()
will cause changes to the runtime.