"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.debounceTime = void 0;
const async_js_1 = require("../scheduler/async.js");
const Observable_js_1 = require("../Observable.js");
const executeSchedule_js_1 = require("../util/executeSchedule.js");
function debounceTime(dueTime, scheduler = async_js_1.asyncScheduler) {
    return (source) => new Observable_js_1.Observable((destination) => {
        let lastValue;
        let activeTask;
        source.subscribe((0, Observable_js_1.operate)({
            destination,
            next: (value) => {
                lastValue = value;
                activeTask?.unsubscribe();
                activeTask = (0, executeSchedule_js_1.executeSchedule)(destination, scheduler, () => {
                    activeTask = undefined;
                    const v = lastValue;
                    lastValue = null;
                    destination.next(v);
                }, dueTime);
            },
            complete: () => {
                if (activeTask) {
                    destination.next(lastValue);
                }
                destination.complete();
            },
            finalize: () => {
                lastValue = activeTask = null;
            },
        }));
    });
}
exports.debounceTime = debounceTime;