For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/array/reduceWhile.md.

reduceWhile

Like reduce but stops early when the predicate returns false.

The predicate receives the current accumulator and element. When it returns false, the current accumulator is returned without processing the remaining elements.

// Sum until we hit a negative number
reduceWhile(
  [1, 2, 3, -1, 5],
  (acc, n) => n >= 0,
  (acc, n) => acc + n,
  0,
)
// 6

Usage

reduceWhile<T, R>(array: readonly T[], predicate: (accumulator: R, value: T) => boolean, fn: (accumulator: R, value: T, index: number) => R, initial: R)

Like reduce but stops early when the predicate returns false.

The predicate receives the current accumulator and element. When it returns false, the current accumulator is returned without processing the remaining elements.

import { reduceWhile } from 'massaman'
// or:  import { reduceWhile } from 'massaman/array'

// Sum until we hit a negative number
reduceWhile(
  [1, 2, 3, -1, 5],
  (acc, n) => n >= 0,
  (acc, n) => acc + n,
  0,
)
// 6

Parameters

arrayreadonly T[]required

the source array.

predicate(accumulator: R, value: T) => booleanrequired

the condition used to select behavior.

fn(accumulator: R, value: T, index: number) => Rrequired

the function to apply.

initialRrequired

the initial accumulator value.

Returns

the accumulated value when the input ends or the predicate first returns false.

R