Hyperlinkv0.8.0-beta.28

Array

Array.scanconsteffect/Array.ts:716
<B, A>(b: B, f: (b: B, a: A) => B): (
  self: Iterable<A>
) => NonEmptyArray<B>
<A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): NonEmptyArray<B>

Folds left-to-right while keeping every intermediate accumulator value.

When to use

Use to compute a running accumulator where each intermediate value is needed.

Details

The output length is input.length + 1 because it starts with the initial value. The result is always a NonEmptyArray. Use reduce if you only need the final accumulated value.

Example (Running totals)

import { Array } from "effect"

const result = Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value)
console.log(result) // [0, 1, 3, 6, 10]
Source effect/Array.ts:71612 lines
export const scan: {
  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<A>) => NonEmptyArray<B>
  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): NonEmptyArray<B>
} = dual(3, <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): NonEmptyArray<B> => {
  const out: NonEmptyArray<B> = [b]
  let i = 0
  for (const a of self) {
    out[i + 1] = f(out[i], a)
    i++
  }
  return out
})