UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

51 lines 1.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DebounceTransformer = void 0; /** * The transformer implementation for {@link debounce:function}. * * @group Transformers * @see {@link debounce:function} */ 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); } } exports.DebounceTransformer = DebounceTransformer; //# sourceMappingURL=Transformer.js.map