MCPcopy Create free account
hub / github.com/Effect-TS/effect / reduceWhileEffect

Function reduceWhileEffect

packages/effect/src/Sink.ts:1286–1318  ·  view source on GitHub ↗
(
  initial: LazyArg<S>,
  predicate: Predicate<S>,
  f: (s: S, input: In) => Effect.Effect<S, E, R>
)

Source from the content-addressed store, hash-verified

1284 * @since 4.0.0
1285 */
1286export const reduceWhileEffect = <S, In, E, R>(
1287 initial: LazyArg<S>,
1288 predicate: Predicate<S>,
1289 f: (s: S, input: In) => Effect.Effect<S, E, R>
1290): Sink<S, In, In, E, R> =>
1291 fromTransform((upstream) => {
1292 let state = initial()
1293 let leftover: NonEmptyReadonlyArray<In> | undefined = undefined
1294 if (!predicate(state)) {
1295 return Effect.succeed([state] as const)
1296 }
1297 return upstream.pipe(
1298 Effect.flatMap((arr) => {
1299 let i = 0
1300 return Effect.whileLoop({
1301 while: () => i < arr.length,
1302 body: constant(Effect.flatMap(Effect.suspend(() => f(state, arr[i++])), (s) => {
1303 state = s
1304 if (!predicate(state)) {
1305 if (i < arr.length) {
1306 leftover = arr.slice(i) as any
1307 }
1308 return Cause.done()
1309 }
1310 return Effect.void
1311 })),
1312 step: constVoid
1313 })
1314 }),
1315 Effect.forever({ disableYield: true }),
1316 Pull.catchDone(() => Effect.succeed([state, leftover] as const))
1317 )
1318 })
1319
1320/**
1321 * A sink that reduces non-empty input arrays from the provided `initial` state

Callers 2

reduceEffectFunction · 0.85
findEffectFunction · 0.85

Calls 8

constantFunction · 0.90
initialFunction · 0.85
predicateFunction · 0.85
fromTransformFunction · 0.70
pipeMethod · 0.65
fFunction · 0.50
succeedMethod · 0.45
doneMethod · 0.45

Tested by

no test coverage detected