import { AsyncIterableX } from '../asynciterablex.js'; import { MonoTypeOperatorAsyncFunction } from '../../interfaces.js'; import { wrapWithAbort } from './withabort.js'; import { throwIfAborted } from '../../aborterror.js'; /** @ignore */ export class ThrottleAsyncIterable extends AsyncIterableX { private _source: AsyncIterable; private _time: number; constructor(source: AsyncIterable, time: number) { super(); this._source = source; this._time = time; } async *[Symbol.asyncIterator](signal?: AbortSignal) { throwIfAborted(signal); let currentTime; let previousTime; for await (const item of wrapWithAbort(this._source, signal)) { currentTime = Date.now(); if (!previousTime || currentTime - previousTime > this._time) { previousTime = currentTime; yield item; } } } } /** * Throttles the source async-iterable sequence so that it doesn't emit more than one value during the given timeframe. * * @template TSource The type of elements in the source sequence. * @param {number} time The time in milliseconds to throttle the source sequence. * @returns {MonoTypeOperatorAsyncFunction} The source sequence throttled by the given timeframe. */ export function throttle(time: number): MonoTypeOperatorAsyncFunction { return function throttleOperatorFunction( source: AsyncIterable ): AsyncIterableX { return new ThrottleAsyncIterable(source, time); }; }