JSFiddle - React, Tailwind, and code Playground
by mattpodwysocki
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/2.2.3/rx.js"></script>
JavaScript
Rx.Observable.prototype.scan = function (/* seed, accumulator */) {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return Rx.Observable.createWithDisposable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
function add(x, y) { return x + y; }
function createObserver(num) {
return Rx.Observer.create(
function (x) {
console.log('next ' + num + ':' + x);
},
function (e) {
console.log(e.message);
},
function () {
console.log('completed ' + num);
}
);
}
// Usage
var obs1 = Rx.Observable.empty().scan(add);
var obs2 = Rx.Observable.empty().scan(0, add);
var obs3 = Rx.Observable.range(1, 3).scan(add);
var obs4 = Rx.Observable.range(1, 3).scan(0,...