Hyperlinkv0.8.0-beta.28

Reducer

Reducer.makefunctioneffect/Reducer.ts:121
<A>(
  combine: (self: A, that: A) => A,
  initialValue: A,
  combineAll?: (collection: Iterable<A>) => A
): Reducer<A>

Creates a Reducer from a combine function and an initialValue.

When to use

Use when you have a custom reducing operation not covered by a pre-built reducer.

  • You want to provide an optimized combineAll (e.g. short-circuiting on a known absorbing element like 0 for multiplication).

Details

  • If combineAll is omitted, a default left-to-right fold starting from initialValue is used.
  • If combineAll is provided, it completely replaces the default fold.

Example (Multiplying with short-circuit)

import { Reducer } from "effect"

const Product = Reducer.make<number>(
  (a, b) => a * b,
  1,
  (collection) => {
    let acc = 1
    for (const n of collection) {
      if (n === 0) return 0
      acc *= n
    }
    return acc
  }
)

console.log(Product.combineAll([2, 3, 4]))
// Output: 24

console.log(Product.combineAll([2, 0, 4]))
// Output: 0
constructorsReducerflip
Source effect/Reducer.ts:12118 lines
export function make<A>(
  combine: (self: A, that: A) => A,
  initialValue: A,
  combineAll?: (collection: Iterable<A>) => A
): Reducer<A> {
  return {
    combine,
    initialValue,
    combineAll: combineAll ??
      ((collection) => {
        let out = initialValue
        for (const value of collection) {
          out = combine(out, value)
        }
        return out
      })
  }
}
Referenced by 22 symbols