"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.zipWithPar = exports.zipWithPar_ = void 0;
// ets_tracing: off
// ets_tracing: off
const cause_1 = require("../Cause/cause");
const core_1 = require("../Fiber/core");
const core_2 = require("./core");
const core_scope_1 = require("./core-scope");
const map_1 = require("./map");
/**
 * Sequentially zips this effect with the specified effect using the
 * specified combiner function.
 */
function zipWithPar_(a, b, f, __trace) {
    const g = (b, a) => f(a, b);
    return (0, core_scope_1.transplant)((graft) => (0, core_2.descriptorWith)((d) => (0, core_scope_1.raceWith_)(graft(a), graft(b), (ex, fi) => coordinateZipPar(d.id, f, true, ex, fi), (ex, fi) => coordinateZipPar(d.id, g, false, ex, fi), __trace)));
}
exports.zipWithPar_ = zipWithPar_;
function coordinateZipPar(fiberId, f, leftWinner, winner, loser) {
    switch (winner._tag) {
        case "Success": {
            return (0, map_1.map_)((0, core_1.join)(loser), (y) => f(winner.value, y));
        }
        case "Failure": {
            return (0, core_2.chain_)(loser.interruptAs(fiberId), (e) => {
                switch (e._tag) {
                    case "Success": {
                        return (0, core_2.halt)(winner.cause);
                    }
                    case "Failure": {
                        return leftWinner
                            ? (0, core_2.halt)((0, cause_1.both)(winner.cause, e.cause))
                            : (0, core_2.halt)((0, cause_1.both)(e.cause, winner.cause));
                    }
                }
            });
        }
    }
}
/**
 * Sequentially zips this effect with the specified effect using the
 * specified combiner function.
 */
function zipWithPar(b, f, __trace) {
    return (a) => zipWithPar_(a, b, f, __trace);
}
exports.zipWithPar = zipWithPar;
//# sourceMappingURL=zipWithPar.js.map