"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addListeners = exports.addListener = void 0;
const ShouldNeverHappenError_1 = require("../exception/ShouldNeverHappenError");
const callAll_1 = require("../util/call/callAll");
function addListener(listenable, listener) {
    const { $listener, $unlisten } = listenable;
    $listener.push(listener);
    const unlisten = listener(listenable);
    $unlisten.push(unlisten);
    return () => {
        const i = $listener.indexOf(listener);
        if (i > -1) {
            const unlisten = $unlisten[i];
            unlisten();
            $listener.splice(i, 1);
            $unlisten.splice(i, 1);
        }
        else {
            throw new ShouldNeverHappenError_1.ShouldNeverHappenError();
        }
    };
}
exports.addListener = addListener;
function addListeners(listenable, listeners) {
    const all_unlisten = [];
    for (const listener of listeners) {
        const unlisten = addListener(listenable, listener);
        all_unlisten.push(unlisten);
    }
    const unlisten = (0, callAll_1.callAll)(all_unlisten);
    return unlisten;
}
exports.addListeners = addListeners;
//# sourceMappingURL=addListener.js.map