"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reduce = void 0;
// ets_tracing: off
const CK = __importStar(require("../../../Collections/Immutable/Chunk"));
const Tp = __importStar(require("../../../Collections/Immutable/Tuple"));
const CH = __importStar(require("../Channel"));
const C = __importStar(require("./core"));
/**
 * A sink that folds its inputs with the provided function, termination predicate and initial state.
 */
function reduce(z, cont, f) {
    const reduceChunkSplit = (z, chunk) => (cont) => (f) => {
        const reduce = (s, chunk, idx, len) => {
            if (idx === len) {
                return Tp.tuple(s, CK.empty());
            }
            else {
                const s1 = f(s, CK.unsafeGet_(chunk, idx));
                if (cont(s1)) {
                    return reduce(s1, chunk, idx + 1, len);
                }
                else {
                    return Tp.tuple(s1, CK.drop_(chunk, idx + 1));
                }
            }
        };
        return reduce(z, chunk, 0, CK.size(chunk));
    };
    const reader = (s) => {
        if (!cont(s)) {
            return CH.end(s);
        }
        else {
            return CH.readWith((_in) => {
                const { tuple: [nextS, leftovers] } = reduceChunkSplit(s, _in)(cont)(f);
                if (!CK.isEmpty(leftovers)) {
                    return CH.as_(CH.write(leftovers), nextS);
                }
                else {
                    return reader(nextS);
                }
            }, (err) => CH.fail(err), (_) => CH.end(s));
        }
    };
    return new C.Sink(reader(z));
}
exports.reduce = reduce;
//# sourceMappingURL=reduce.js.map