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

Function reduceWhile

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

Source from the content-addressed store, hash-verified

1313 * @since 4.0.0
1314 */
1315export const reduceWhile = <S, In>(
1316 initial: LazyArg<S>,
1317 predicate: Predicate<S>,
1318 f: (s: S, input: In) => S
1319): Sink<S, In, In> =>
1320 fromTransform((upstream) => {
1321 let state = initial()
1322 let leftover: NonEmptyReadonlyArray<In> | undefined = undefined
1323 if (!predicate(state)) {
1324 return Effect.succeed([state] as const)
1325 }
1326 return upstream.pipe(
1327 Effect.flatMap((arr) => {
1328 for (let i = 0; i < arr.length; i++) {
1329 state = f(state, arr[i])
1330 if (!predicate(state)) {
1331 if ((i + 1) < arr.length) {
1332 leftover = arr.slice(i + 1) as any
1333 }
1334 return Cause.done()
1335 }
1336 }
1337 return Effect.void
1338 }),
1339 Effect.forever({ disableYield: true }),
1340 Pull.catchDone(() => Effect.succeed([state, leftover] as const))
1341 )
1342 })
1343
1344/**
1345 * A sink that effectfully reduces input elements from the provided `initial`

Callers 2

Sink.tsFile · 0.85
findFunction · 0.85

Calls 8

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