import * as tsplus_module_1 from "@effect/core/stream/Sink/operations/suspend";
import * as tsplus_module_2 from "@effect/core/stream/Channel/operations/fail";
import * as tsplus_module_3 from "@effect/core/stream/Channel/operations/succeedNow";
import * as tsplus_module_4 from "@effect/core/stream/Channel/operations/readWith";
import { SinkInternal } from "@effect/core/stream/Sink/operations/_internal/SinkInternal";
/**
 * A sink that folds its input chunks with the provided function, termination
 * predicate and initial state. The `cont` condition is checked only for the
 * initial value and at the end of processing of each chunk. `f` and `cont`
 * must preserve chunking-invariance.
 *
 * @tsplus static ets/Sink/Ops foldChunks
 */

export function foldChunks(z, cont, f, __tsplusTrace) {
  return tsplus_module_1.suspend(() => new SinkInternal(reader(z(), cont, f, __tsplusTrace)), __tsplusTrace);
}

function reader(z, cont, f, __tsplusTrace) {
  return cont(z) ? tsplus_module_4.readWith(chunk => {
    const nextS = f(z, chunk);
    return reader(nextS, cont, f, __tsplusTrace);
  }, err => tsplus_module_2.fail(() => err), () => tsplus_module_3.succeedNow(z)) : tsplus_module_3.succeedNow(z);
}
//# sourceMappingURL=foldChunks.mjs.map