Hyperlinkv0.8.0-beta.28

Struct

Struct.makeReducerfunctioneffect/Struct.ts:935
<A>(
  reducers: { readonly [K in keyof A]: Reducer.Reducer<A[K]> },
  options?: {
    readonly omitKeyWhen?: ((a: A[keyof A]) => boolean) | undefined
  }
): Reducer.Reducer<A>

Creates a Reducer for a struct shape by providing a Reducer for each property. The initial value is derived from each property's Reducer.initialValue. When reducing a collection of structs, each property is combined independently.

When to use

Use when you need to fold same-shape records by accumulating each property independently into one summary record.

Details

Pass omitKeyWhen to drop properties whose reduced value matches a predicate.

Example (Reducing a collection of structs)

import { Number, String, Struct } from "effect"

const R = Struct.makeReducer<{ readonly n: number; readonly s: string }>({
  n: Number.ReducerSum,
  s: String.ReducerConcat
})

const result = R.combineAll([
  { n: 1, s: "a" },
  { n: 2, s: "b" },
  { n: 3, s: "c" }
])
console.log(result) // { n: 6, s: "abc" }
Source effect/Struct.ts:93515 lines
export function makeReducer<A>(
  reducers: { readonly [K in keyof A]: Reducer.Reducer<A[K]> },
  options?: {
    readonly omitKeyWhen?: ((a: A[keyof A]) => boolean) | undefined
  }
): Reducer.Reducer<A> {
  const combine = makeCombiner(reducers, options).combine
  const initialValue = {} as A
  for (const key of Reflect.ownKeys(reducers) as Array<keyof A>) {
    const iv = reducers[key].initialValue
    if (options?.omitKeyWhen?.(iv)) continue
    initialValue[key] = iv
  }
  return Reducer.make(combine, initialValue)
}