Hyperlinkv0.8.0-beta.28

Iterable

Iterable.flatMapNullishOrconsteffect/Iterable.ts:1990
<A, B>(f: (a: A) => B): (self: Iterable<A>) => Iterable<NonNullable<B>>
<A, B>(self: Iterable<A>, f: (a: A) => B): Iterable<NonNullable<B>>

Transforms elements using a function that may return null or undefined, filtering out the null/undefined results.

When to use

Use when working with APIs or functions that return nullable values, providing a clean way to filter out null or undefined while transforming.

Example (Flat mapping nullable results)

import { Iterable } from "effect"

// Extract valid elements from nullable function results
const data = ["1", "2", "invalid", "4"]
const parsed = Iterable.flatMapNullishOr(data, (s) => {
  const num = parseInt(s)
  return isNaN(num) ? null : num * 2
})
console.log(Array.from(parsed)) // [2, 4, 8]

// Safe property access
const objects = [
  { nested: { value: 10 } },
  { nested: null },
  { nested: { value: 20 } },
  {}
]
const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value)
console.log(Array.from(values)) // [10, 20]

// Working with Map.get (returns undefined for missing keys)
const map = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
])
const keys = ["a", "x", "b", "y", "c"]
const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key))
console.log(Array.from(foundValues)) // [1, 2, 3]
sequencing
export const flatMapNullishOr: {
  <A, B>(f: (a: A) => B): (self: Iterable<A>) => Iterable<NonNullable<B>>
  <A, B>(self: Iterable<A>, f: (a: A) => B): Iterable<NonNullable<B>>
} = dual(
  2,
  <A, B>(self: Iterable<A>, f: (a: A) => B): Iterable<NonNullable<B>> =>
    filterMap(self, (a) => {
      const b = f(a)
      return b == null ? R.failVoid : R.succeed(b)
    })
)