ix
Version:
The Interactive Extensions for JavaScript
69 lines (67 loc) • 2.73 kB
JavaScript
import { __asyncGenerator, __asyncValues, __await } from "tslib";
import { AsyncIterableX, interval, concat, of } from '../index.mjs';
import { map } from './map.mjs';
import { merge } from '../merge.mjs';
import { wrapWithAbort } from './withabort.mjs';
const timerEvent = {};
const ended = {};
class BufferCountOrTime extends AsyncIterableX {
constructor(source, bufferSize, maxWaitTime) {
super();
this.source = source;
this.bufferSize = bufferSize;
this.maxWaitTime = maxWaitTime;
}
[Symbol.asyncIterator](signal) {
return __asyncGenerator(this, arguments, function* _a() {
var _b, e_1, _c, _d;
const buffer = [];
const timer = interval(this.maxWaitTime).pipe(map(() => timerEvent));
const source = concat(this.source, of(ended));
const merged = merge(source, timer);
try {
for (var _e = true, _f = __asyncValues(wrapWithAbort(merged, signal)), _g; _g = yield __await(_f.next()), _b = _g.done, !_b; _e = true) {
_d = _g.value;
_e = false;
const item = _d;
if (item === ended) {
break;
}
if (item !== timerEvent) {
buffer.push(item);
}
if (buffer.length >= this.bufferSize || (buffer.length && item === timerEvent)) {
yield yield __await(buffer.slice());
buffer.length = 0;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_e && !_b && (_c = _f.return)) yield __await(_c.call(_f));
}
finally { if (e_1) throw e_1.error; }
}
if (buffer.length) {
yield yield __await(buffer);
}
});
}
}
/**
* Projects each element of an async-iterable sequence into consecutive buffers
* which are emitted when either the threshold count or time is met.
*
* @template TSource The type of elements in the source sequence.
* @param {number} count The size of the buffer.
* @param {number} time The threshold number of milliseconds to wait before flushing a non-full buffer
* @returns {OperatorAsyncFunction<TSource, TSource[]>} An operator which returns an async-iterable sequence
* of buffers
*/
export function bufferCountOrTime(count, time) {
return function bufferOperatorFunction(source) {
return new BufferCountOrTime(source, count, time);
};
}
//# sourceMappingURL=buffercountortime.mjs.map