Hyperlinkv0.8.0-beta.28

Struct

Struct.makeCombinerfunctioneffect/Struct.ts:878
<A>(
  combiners: { readonly [K in keyof A]: Combiner.Combiner<A[K]> },
  options?: {
    readonly omitKeyWhen?: ((a: A[keyof A]) => boolean) | undefined
  }
): Combiner.Combiner<A>

Creates a Combiner for a struct shape by providing a Combiner for each property. When two structs are combined, each property is merged using its corresponding combiner.

When to use

Use when you need to merge two same-shape records by combining each property independently, such as summing counters or concatenating strings.

Details

Pass omitKeyWhen to drop properties whose merged value matches a predicate, such as omitting zero counters.

Example (Combining struct properties)

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

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

const result = C.combine({ n: 1, s: "hello" }, { n: 2, s: " world" })
console.log(result) // { n: 3, s: "hello world" }
combiningmakeReducer
Source effect/Struct.ts:87818 lines
export function makeCombiner<A>(
  combiners: { readonly [K in keyof A]: Combiner.Combiner<A[K]> },
  options?: {
    readonly omitKeyWhen?: ((a: A[keyof A]) => boolean) | undefined
  }
): Combiner.Combiner<A> {
  const omitKeyWhen = options?.omitKeyWhen ?? (() => false)
  return Combiner.make((self, that) => {
    const keys = Reflect.ownKeys(combiners) as Array<keyof A>
    const out = {} as A
    for (const key of keys) {
      const merge = combiners[key].combine(self[key], that[key])
      if (omitKeyWhen(merge)) continue
      out[key] = merge
    }
    return out
  })
}
Referenced by 1 symbols