Hyperlinkv0.8.0-beta.28

Array

Array.mapAccumconsteffect/Array.ts:4562
<S, A, B, I extends Iterable<A> = Iterable<A>>(
  s: S,
  f: (s: S, a: ReadonlyArray.Infer<I>, i: number) => readonly [S, B]
): (self: I) => [state: S, mappedArray: ReadonlyArray.With<I, B>]
<S, A, B, I extends Iterable<A> = Iterable<A>>(
  self: I,
  s: S,
  f: (s: S, a: ReadonlyArray.Infer<I>, i: number) => readonly [S, B]
): [state: S, mappedArray: ReadonlyArray.With<I, B>]

Maps over an array while threading an accumulator through each step, returning both the final state and the mapped array.

When to use

Use when you need to map while threading state through each element and keep the final state.

Details

Combines map and reduce in a single pass. The callback receives the current state, element, and index, and returns [nextState, mappedValue]. The result is [finalState, mappedArray]. This can be used in both data-first and data-last style.

Example (Running sum alongside mapped values)

import { Array } from "effect"

const result = Array.mapAccum([1, 2, 3], 0, (acc, n) => [acc + n, acc + n])
console.log(result) // [6, [1, 3, 6]]
foldingscanreduce
Source effect/Array.ts:456225 lines
export const mapAccum: {
  <S, A, B, I extends Iterable<A> = Iterable<A>>(
    s: S,
    f: (s: S, a: ReadonlyArray.Infer<I>, i: number) => readonly [S, B]
  ): (self: I) => [state: S, mappedArray: ReadonlyArray.With<I, B>]
  <S, A, B, I extends Iterable<A> = Iterable<A>>(
    self: I,
    s: S,
    f: (s: S, a: ReadonlyArray.Infer<I>, i: number) => readonly [S, B]
  ): [state: S, mappedArray: ReadonlyArray.With<I, B>]
} = dual(
  3,
  <S, A, B>(self: Iterable<A>, s: S, f: (s: S, a: A, i: number) => [S, B]): [state: S, mappedArray: Array<B>] => {
    let i = 0
    let s1 = s
    const out: Array<B> = []
    for (const a of self) {
      const r = f(s1, a, i)
      s1 = r[0]
      out.push(r[1])
      i++
    }
    return [s1, out]
  }
)
Referenced by 1 symbols