"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.first = void 0;
const Observable_js_1 = require("../Observable.js");
const EmptyError_js_1 = require("../util/EmptyError.js");
function first(predicate, defaultValue) {
    const hasDefaultValue = arguments.length >= 2;
    return (source) => new Observable_js_1.Observable((destination) => {
        let index = 0;
        const operatorSubscriber = (0, Observable_js_1.operate)({
            destination,
            next: (value) => {
                const passed = predicate ? predicate(value, index++, source) : true;
                if (passed) {
                    operatorSubscriber.unsubscribe();
                    destination.next(value);
                    destination.complete();
                }
            },
            complete: () => {
                if (hasDefaultValue) {
                    destination.next(defaultValue);
                    destination.complete();
                }
                else {
                    destination.error(new EmptyError_js_1.EmptyError());
                }
            },
        });
        source.subscribe(operatorSubscriber);
    });
}
exports.first = first;