Hyperlinkv0.8.0-beta.28

Option

Option.reduceCompactconsteffect/Option.ts:1838
<B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<Option<A>>) => B
<A, B>(self: Iterable<Option<A>>, b: B, f: (b: B, a: A) => B): B

Reduces an iterable of Options to a single value, skipping None entries.

When to use

Use when you need to aggregate values from a collection where some may be absent.

Details

  • Iterates through the collection, applying f only to Some values
  • None values are skipped entirely
  • Returns the accumulated result

Example (Summing present values)

import { Option, pipe } from "effect"

const items = [Option.some(1), Option.none(), Option.some(2), Option.none()]

console.log(pipe(items, Option.reduceCompact(0, (b, a) => b + a)))
// Output: 3
reducing
Source effect/Option.ts:183815 lines
export const reduceCompact: {
  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<Option<A>>) => B
  <A, B>(self: Iterable<Option<A>>, b: B, f: (b: B, a: A) => B): B
} = dual(
  3,
  <A, B>(self: Iterable<Option<A>>, b: B, f: (b: B, a: A) => B): B => {
    let out: B = b
    for (const oa of self) {
      if (isSome(oa)) {
        out = f(out, oa.value)
      }
    }
    return out
  }
)