UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

47 lines 1.47 kB
/** * The transformer implementation for {@link debounce:function}. * * @group Transformers * @see {@link debounce:function} */ export class DebounceTransformer { #behaviors; #state; constructor(ms, behaviors) { this.#behaviors = behaviors; this.#state = this.#reduceState('init', { ms, queued: false }); } transform(chunk, controller) { this.#preTimer(chunk, controller); this.#timer(chunk, controller); } flush() { clearTimeout(this.#state.timer); } #preTimer(chunk, controller) { clearTimeout(this.#state.timer); this.#state = this.#reduceState('preTimer', { ...this.#state, queued: false, }, chunk, controller); } #timer(chunk, controller) { this.#state = { ...this.#state, timer: setTimeout(() => this.#postTimer(chunk, controller), this.#state.ms), }; } #postTimer(chunk, controller) { clearTimeout(this.#state.timer); this.#state = this.#reduceState('postTimer', { ...this.#state, timer: undefined, }, chunk, controller); } #reduceState(stage, state, chunk, controller) { return this.#behaviors.reduce((state, behavior) => // eslint-disable-next-line @typescript-eslint/no-non-null-assertion behavior[stage]?.(state, chunk, controller) || state, state); } } //# sourceMappingURL=Transformer.js.map