"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.fold = 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 fold(z, contFn, f) {
    const foldChunkSplit = (z, chunk, contFn, f) => {
        const fold = (s, chunk, idx, len) => {
            if (idx === len) {
                return Tp.tuple(s, CK.empty());
            }
            else {
                const s1 = f(s, CK.unsafeGet_(chunk, idx));
                if (contFn(s1)) {
                    return fold(s1, chunk, idx + 1, len);
                }
                else {
                    return Tp.tuple(s1, CK.drop_(chunk, idx + 1));
                }
            }
        };
        return fold(z, chunk, 0, CK.size(chunk));
    };
    const reader = (s) => {
        if (!contFn(s)) {
            return CH.end(s);
        }
        return CH.readWith((in_) => {
            const { tuple: [nextS, leftovers] } = foldChunkSplit(s, in_, contFn, 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.fold = fold;
//# sourceMappingURL=fold.js.map