75 lines
1.7 KiB
JavaScript
75 lines
1.7 KiB
JavaScript
|
'use strict';
|
||
|
|
||
|
Object.defineProperty(exports, "__esModule", {
|
||
|
value: true
|
||
|
});
|
||
|
exports.iterate = iterate;
|
||
|
|
||
|
var _Stream = require('../Stream');
|
||
|
|
||
|
var _Stream2 = _interopRequireDefault(_Stream);
|
||
|
|
||
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||
|
|
||
|
/**
|
||
|
* 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}
|
||
|
*/
|
||
|
function iterate(f, x) {
|
||
|
return new _Stream2.default(new IterateSource(f, x));
|
||
|
} /** @license MIT License (c) copyright 2010-2016 original author or authors */
|
||
|
/** @author Brian Cavalier */
|
||
|
/** @author John Hann */
|
||
|
|
||
|
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);
|
||
|
}
|