"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sequenceEqual = void 0;
const Observable_js_1 = require("../Observable.js");
function sequenceEqual(compareTo, comparator = (a, b) => a === b) {
    return (source) => new Observable_js_1.Observable((destination) => {
        const aState = createState();
        const bState = createState();
        const emit = (isEqual) => {
            destination.next(isEqual);
            destination.complete();
        };
        const createSubscriber = (selfState, otherState) => {
            const sequenceEqualSubscriber = (0, Observable_js_1.operate)({
                destination,
                next: (a) => {
                    const { buffer, complete } = otherState;
                    if (buffer.length === 0) {
                        complete ? emit(false) : selfState.buffer.push(a);
                    }
                    else {
                        !comparator(a, buffer.shift()) && emit(false);
                    }
                },
                complete: () => {
                    selfState.complete = true;
                    const { complete, buffer } = otherState;
                    complete && emit(buffer.length === 0);
                    sequenceEqualSubscriber?.unsubscribe();
                },
            });
            return sequenceEqualSubscriber;
        };
        source.subscribe(createSubscriber(aState, bState));
        (0, Observable_js_1.from)(compareTo).subscribe(createSubscriber(bState, aState));
    });
}
exports.sequenceEqual = sequenceEqual;
function createState() {
    return {
        buffer: [],
        complete: false,
    };
}