UNPKG

@zkochan/pnpm

Version:

Fast, disk space efficient package manager

67 lines (52 loc) 1.44 kB
/** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ import Stream from '../Stream' /** * Compute a stream by iteratively calling f to produce values * Event times may be controlled by returning a Promise from f * @param {function(x:*):*|Promise<*>} f * @param {*} x initial value * @returns {Stream} */ export function iterate (f, x) { return new Stream(new IterateSource(f, x)) } function IterateSource (f, x) { this.f = f this.value = x } IterateSource.prototype.run = function (sink, scheduler) { return new Iterate(this.f, this.value, sink, scheduler) } function Iterate (f, initial, sink, scheduler) { this.f = f this.sink = sink this.scheduler = scheduler this.active = true var x = initial var self = this function err (e) { self.sink.error(self.scheduler.now(), e) } function start (iterate) { return stepIterate(iterate, x) } Promise.resolve(this).then(start).catch(err) } Iterate.prototype.dispose = function () { this.active = false } function stepIterate (iterate, x) { iterate.sink.event(iterate.scheduler.now(), x) if (!iterate.active) { return x } var f = iterate.f return Promise.resolve(f(x)).then(function (y) { return continueIterate(iterate, y) }) } function continueIterate (iterate, x) { return !iterate.active ? iterate.value : stepIterate(iterate, x) }