Hyperlinkv0.8.0-beta.28

TxHashMap

TxHashMap.flatMapconsteffect/TxHashMap.ts:1992
<A, V, K>(f: (value: V, key: K) => Effect.Effect<TxHashMap<K, A>>): (
  self: TxHashMap<K, V>
) => Effect.Effect<TxHashMap<K, A>>
<K, V, A>(
  self: TxHashMap<K, V>,
  f: (value: V, key: K) => Effect.Effect<TxHashMap<K, A>>
): Effect.Effect<TxHashMap<K, A>>

Maps each entry effectfully to a TxHashMap and flattens the produced maps.

Details

This function returns a new TxHashMap reference with the flattened results. The original TxHashMap is not modified.

Example (Flat mapping entries)

import { Effect, TxHashMap } from "effect"

const program = Effect.gen(function*() {
  // Create a department-employee map
  const departments = yield* TxHashMap.make(
    ["engineering", ["alice", "bob"]],
    ["marketing", ["charlie", "diana"]]
  )

  // Expand each department into individual employee entries with metadata
  const employeeDetails = yield* TxHashMap.flatMap(
    departments,
    (employees, department) =>
      Effect.gen(function*() {
        const employeeMap = yield* TxHashMap.empty<
          string,
          { department: string; role: string }
        >()
        for (let i = 0; i < employees.length; i++) {
          const employee = employees[i]
          const role = i === 0 ? "lead" : "member"
          yield* TxHashMap.set(employeeMap, employee, { department, role })
        }
        return employeeMap
      })
  )

  // Check the flattened result
  const alice = yield* TxHashMap.get(employeeDetails, "alice")
  console.log(alice) // Option.some({ department: "engineering", role: "lead" })

  const charlie = yield* TxHashMap.get(employeeDetails, "charlie")
  console.log(charlie) // Option.some({ department: "marketing", role: "lead" })

  const size = yield* TxHashMap.size(employeeDetails)
  console.log(size) // 4 (all employees)
})
combinators
export const flatMap: {
  <A, V, K>(
    f: (value: V, key: K) => Effect.Effect<TxHashMap<K, A>>
  ): (self: TxHashMap<K, V>) => Effect.Effect<TxHashMap<K, A>>
  <K, V, A>(
    self: TxHashMap<K, V>,
    f: (value: V, key: K) => Effect.Effect<TxHashMap<K, A>>
  ): Effect.Effect<TxHashMap<K, A>>
} = dual(
  2,
  <K, V, A>(
    self: TxHashMap<K, V>,
    f: (value: V, key: K) => Effect.Effect<TxHashMap<K, A>>
  ): Effect.Effect<TxHashMap<K, A>> =>
    Effect.gen(function*() {
      const currentMap = yield* TxRef.get(self.ref)
      const result = yield* empty<K, A>()

      const mapEntries = HashMap.toEntries(currentMap)
      for (const [key, value] of mapEntries) {
        const newMap = yield* f(value, key)
        const newEntries = yield* entries(newMap)
        yield* setMany(result, newEntries)
      }

      return result
    }).pipe(Effect.tx)
)