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

Function reduceWhileEffect

packages/effect/src/Sink.ts:1352–1384  ·  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

1350 * @since 4.0.0
1351 */
1352export const reduceWhileEffect = <S, In, E, R>(
1353 initial: LazyArg<S>,
1354 predicate: Predicate<S>,
1355 f: (s: S, input: In) => Effect.Effect<S, E, R>
1356): Sink<S, In, In, E, R> =>
1357 fromTransform((upstream) => {
1358 let state = initial()
1359 let leftover: NonEmptyReadonlyArray<In> | undefined = undefined
1360 if (!predicate(state)) {
1361 return Effect.succeed([state] as const)
1362 }
1363 return upstream.pipe(
1364 Effect.flatMap((arr) => {
1365 let i = 0
1366 return Effect.whileLoop({
1367 while: () => i < arr.length,
1368 body: constant(Effect.flatMap(Effect.suspend(() => f(state, arr[i++])), (s) => {
1369 state = s
1370 if (!predicate(state)) {
1371 if (i < arr.length) {
1372 leftover = arr.slice(i) as any
1373 }
1374 return Cause.done()
1375 }
1376 return Effect.void
1377 })),
1378 step: constVoid
1379 })
1380 }),
1381 Effect.forever({ disableYield: true }),
1382 Pull.catchDone(() => Effect.succeed([state, leftover] as const))
1383 )
1384 })
1385
1386/**
1387 * A sink that reduces non-empty input arrays from the provided `initial` state

Callers 2

reduceEffectFunction · 0.85
findEffectFunction · 0.85

Calls 9

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

Tested by

no test coverage detected