xstream-tuplewise
Version:
An xstream operator that groups consecutive events into N-tuples
53 lines (50 loc) • 1.06 kB
JavaScript
import { Stream } from 'xstream';
class TuplewiseOperator {
constructor(n, ins) {
this.n = n;
this.ins = ins;
this.type = 'tuplewise';
this.buf = [];
this.out = null;
}
_start(out) {
this.out = out;
this.ins._add(this);
}
_stop() {
this.ins._remove(this);
this.out = null;
this.buf = [];
}
_n(t) {
const u = this.out;
if (!u)
return;
this.buf.push(t);
if (this.buf.length >= this.n) {
u._n(this.buf);
this.buf = this.buf.slice(1, this.n);
}
}
_e(err) {
const u = this.out;
if (!u)
return;
u._e(err);
}
_c() {
const u = this.out;
if (!u)
return;
u._c();
}
}
function tuplewise(n) {
return function ($) {
if (n === 0) {
return $.map((_) => []).startWith([]);
}
return new Stream(new TuplewiseOperator(n, $));
};
}
export { tuplewise };