import * as tsplus_module_1 from "@tsplus/stdlib/collections/Chunk/definition";
import * as tsplus_module_2 from "@effect/core/stm/STM/operations/map";
import * as tsplus_module_3 from "@effect/core/stm/STM/operations/flatMap";
import * as tsplus_module_4 from "@tsplus/stdlib/collections/mutable/ListBuffer";
import * as tsplus_module_5 from "@effect/core/stm/STM/operations/succeed";
import * as tsplus_module_6 from "@effect/core/stm/STM/operations/suspend";
/**
 * Loops with the specified transactional function, collecting the results
 * into a list. The moral equivalent of:
 *
 * ```typescript
 * let s  = initial
 * let as = [] as readonly A[]
 *
 * while (cont(s)) {
 *   as = [body(s), ...as]
 *   s  = inc(s)
 * }
 *
 * A.reverse(as)
 * ```
 *
 * @tsplus static ets/STM/Ops loop
 */

export function loop(initial, cont, inc) {
  return body => {
    return tsplus_module_2.map_(loopInternal(initial, cont, inc, body), list => tsplus_module_1.from(list));
  };
}

function loopInternal(initial, cont, inc, body) {
  return tsplus_module_6.suspend(() => {
    const initial0 = initial();
    return cont(initial0) ? tsplus_module_3.flatMap_(body(initial0), a => tsplus_module_2.map_(loopInternal(() => inc(initial0), cont, inc, body), as => {
      as.prepend(a);
      return as;
    })) : tsplus_module_5.succeed(() => tsplus_module_4.ListBuffer.empty());
  });
}
//# sourceMappingURL=loop.mjs.map