"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.elementAt = void 0;
const ArgumentOutOfRangeError_js_1 = require("../util/ArgumentOutOfRangeError.js");
const Observable_js_1 = require("../Observable.js");
function elementAt(index, defaultValue) {
    if (index < 0) {
        throw new ArgumentOutOfRangeError_js_1.ArgumentOutOfRangeError();
    }
    const hasDefaultValue = arguments.length >= 2;
    return (source) => new Observable_js_1.Observable((destination) => {
        let i = 0;
        const operatorSubscriber = (0, Observable_js_1.operate)({
            destination,
            next: (value) => {
                if (i++ === index) {
                    operatorSubscriber.unsubscribe();
                    destination.next(value);
                    destination.complete();
                }
            },
            complete: () => {
                if (!hasDefaultValue) {
                    destination.error(new ArgumentOutOfRangeError_js_1.ArgumentOutOfRangeError());
                }
                else {
                    destination.next(defaultValue);
                    destination.complete();
                }
            },
        });
        source.subscribe(operatorSubscriber);
    });
}
exports.elementAt = elementAt;