84 lines
2.1 KiB
JavaScript
84 lines
2.1 KiB
JavaScript
'use strict';
|
|
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
exports.generate = generate;
|
|
|
|
var _Stream = require('../Stream');
|
|
|
|
var _Stream2 = _interopRequireDefault(_Stream);
|
|
|
|
var _prelude = require('@most/prelude');
|
|
|
|
var base = _interopRequireWildcard(_prelude);
|
|
|
|
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }
|
|
|
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
|
|
/**
|
|
* Compute a stream using an *async* generator, which yields promises
|
|
* to control event times.
|
|
* @param f
|
|
* @returns {Stream}
|
|
*/
|
|
/** @license MIT License (c) copyright 2010-2014 original author or authors */
|
|
/** @author Brian Cavalier */
|
|
/** @author John Hann */
|
|
|
|
function generate(f /*, ...args */) {
|
|
return new _Stream2.default(new GenerateSource(f, base.tail(arguments)));
|
|
}
|
|
|
|
function GenerateSource(f, args) {
|
|
this.f = f;
|
|
this.args = args;
|
|
}
|
|
|
|
GenerateSource.prototype.run = function (sink, scheduler) {
|
|
return new Generate(this.f.apply(void 0, this.args), sink, scheduler);
|
|
};
|
|
|
|
function Generate(iterator, sink, scheduler) {
|
|
this.iterator = iterator;
|
|
this.sink = sink;
|
|
this.scheduler = scheduler;
|
|
this.active = true;
|
|
|
|
var self = this;
|
|
function err(e) {
|
|
self.sink.error(self.scheduler.now(), e);
|
|
}
|
|
|
|
Promise.resolve(this).then(next).catch(err);
|
|
}
|
|
|
|
function next(generate, x) {
|
|
return generate.active ? handle(generate, generate.iterator.next(x)) : x;
|
|
}
|
|
|
|
function handle(generate, result) {
|
|
if (result.done) {
|
|
return generate.sink.end(generate.scheduler.now(), result.value);
|
|
}
|
|
|
|
return Promise.resolve(result.value).then(function (x) {
|
|
return emit(generate, x);
|
|
}, function (e) {
|
|
return error(generate, e);
|
|
});
|
|
}
|
|
|
|
function emit(generate, x) {
|
|
generate.sink.event(generate.scheduler.now(), x);
|
|
return next(generate, x);
|
|
}
|
|
|
|
function error(generate, e) {
|
|
return handle(generate, generate.iterator.throw(e));
|
|
}
|
|
|
|
Generate.prototype.dispose = function () {
|
|
this.active = false;
|
|
}; |