Hyperlinkv0.8.0-beta.28

Sink

Sink.foldconsteffect/Sink.ts:723
<S, In, E = never, R = never>(
  s: LazyArg<S>,
  contFn: Predicate<S>,
  f: (s: S, input: In) => Effect.Effect<S, E, R>
): Sink<S, In, In, E, R>

A sink that folds its inputs with the provided function, termination predicate and initial state.

When to use

Use to accumulate stream input element by element with an effectful step and stop based on the accumulated state.

Details

The initial state is evaluated lazily. Each input element is folded with the effectful function, and the sink continues while contFn returns true. If the sink stops in the middle of a pulled array, the remaining elements from that array are returned as leftovers.

Source effect/Sink.ts:72323 lines
export const fold = <S, In, E = never, R = never>(
  s: LazyArg<S>,
  contFn: Predicate<S>,
  f: (s: S, input: In) => Effect.Effect<S, E, R>
): Sink<S, In, In, E, R> =>
  fromTransform((upstream) => {
    let state = s()
    return Effect.gen(function*() {
      while (true) {
        const arr = yield* upstream
        for (let i = 0; i < arr.length; i++) {
          state = yield* f(state, arr[i])
          if (contFn(state)) continue
          return [
            state,
            (i + 1) < arr.length ? (arr.slice(i + 1) as any) : undefined
          ] as const
        }
      }
    }).pipe(
      Pull.catchDone(() => Effect.succeed<End<S, In>>([state]))
    )
  })
Referenced by 3 symbols