Observable#consecutive
Custom RxJS 5 operator for mapping several consecutively emitted values at once.
Motivation
Say you want to compare every emitted value with previous one.
You could compose such a chain in RxJS:
function compare(a, b) {
return a < b;
}
const comparisonResults = values
.bufferCount(2, 1)
.takeWhile(values => values.length === 2)
.map(([a, b]) => compare(a, b));
consecutive
allows you to write:
const comparisons = values.consecutive(compare);
consecutive
decides based on length of passed function (number of arguments it has in definition) how many values it should buffer. It guarantees that passed function will be always called with as many parameters as it expects.
Alternatively you can provide number of arguments that should be passed to a function (good for functions that have infinite length):
const comparisons = values.consecutive((...args) => {}, 2);
Marbles
const values;
const comparisions = values.consecutive((a, b) => a < b);
const values;
const sums = values.consecutive((a, b, c) => a + b + c);
Usage
consecutive
is exported as function that takes source Observable as first parameter.
You can import it directly and use with let
operator like so:
import { consecutive } from 'rxjs-consecutive-operator';
values.let(v => consecutive(v, fn));
If this feels awkward or you want that operator always near, there is option to monkey patch Observable:
import 'rxjs-consecutive-operator/add';
Observable.consecutive;