API reference@evolu/commonSchedule › foldSchedule

function foldSchedule<Z, Output>(
  initial: Z,
  f: (acc: Z, output: Output) => Z,
): <Input>(schedule: Schedule<Output, Input>) => Schedule<Z, Input>;

Defined in: packages/common/src/Schedule.ts:1531

Folds over the outputs of a schedule, accumulating state.

Each step outputs the accumulated value. Useful for tracking totals, collecting outputs, or building up metadata across attempts.

Folding schedule output

import {
  assertOk,
  exponential,
  foldSchedule,
  minMillis,
  spaced,
  take,
  testCreateDeps,
  type Millis,
} from "@evolu/common";

// Accumulate totals, complete output histories, or structured metadata.
const withTotal = foldSchedule(
  0,
  (total: number, delay: Millis) => total + delay,
)(exponential("100ms"));
const collected = foldSchedule<ReadonlyArray<Millis>, Millis>(
  [],
  (outputs, delay) => [...outputs, delay],
)(take(3)(spaced("1s")));
const counted = foldSchedule(
  { attempts: 0, lastDelay: minMillis },
  (state, delay: Millis) => ({
    attempts: state.attempts + 1,
    lastDelay: delay,
  }),
)(exponential("100ms"));

const deps = testCreateDeps();
const totalStep = withTotal(deps);
totalStep(undefined);
assertOk(totalStep(undefined), [300, 200]);
assertOk(collected(deps)(undefined), [[1000], 1000]);
assertOk(counted(deps)(undefined), [{ attempts: 1, lastDelay: 100 }, 100]);