Hyperlinkv0.8.0-beta.28

Array

Array.scanRightconsteffect/Array.ts:757
<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 right-to-left while keeping every intermediate accumulator value.

When to use

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

Details

The output length is input.length + 1 because it ends with the initial value. The result is always a NonEmptyArray.

Example (Scanning running totals in reverse)

import { Array } from "effect"

const result = Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value)
console.log(result) // [10, 9, 7, 4, 0]
Source effect/Array.ts:75712 lines
export const scanRight: {
  <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 input = fromIterable(self)
  const out: NonEmptyArray<B> = new Array(input.length + 1) as any
  out[input.length] = b
  for (let i = input.length - 1; i >= 0; i--) {
    out[i] = f(out[i + 1], input[i])
  }
  return out
})