Hyperlinkv0.8.0-beta.28

TxHashMap

TxHashMap.modifyconsteffect/TxHashMap.ts:722
<K, V>(key: K, f: (value: V) => V): (
  self: TxHashMap<K, V>
) => Effect.Effect<Option.Option<V>>
<K, V>(self: TxHashMap<K, V>, key: K, f: (value: V) => V): Effect.Effect<
  Option.Option<V>
>

Updates the value for the specified key if it exists, returning the previous value in Some; returns None and leaves the map unchanged when the key is absent.

Details

This function mutates the original TxHashMap by updating the value at the specified key. It does not return a new TxHashMap reference.

Example (Updating existing values)

import { Effect, TxHashMap } from "effect"

const program = Effect.gen(function*() {
  const counters = yield* TxHashMap.make(
    ["downloads", 100],
    ["views", 250]
  )

  // Increment existing counter
  const oldDownloads = yield* TxHashMap.modify(
    counters,
    "downloads",
    (count) => count + 1
  )
  console.log(oldDownloads) // Option.some(100)

  const newDownloads = yield* TxHashMap.get(counters, "downloads")
  console.log(newDownloads) // Option.some(101)

  // Try to modify non-existent key
  const nonExistent = yield* TxHashMap.modify(
    counters,
    "clicks",
    (count) => count + 1
  )
  console.log(nonExistent) // Option.none()

  // Update views counter with direct method call
  yield* TxHashMap.modify(counters, "views", (views) => views * 2)
})
combinators
export const modify: {
  <K, V>(
    key: K,
    f: (value: V) => V
  ): (self: TxHashMap<K, V>) => Effect.Effect<Option.Option<V>>
  <K, V>(self: TxHashMap<K, V>, key: K, f: (value: V) => V): Effect.Effect<Option.Option<V>>
} = dual(
  3,
  <K, V>(
    self: TxHashMap<K, V>,
    key: K,
    f: (value: V) => V
  ): Effect.Effect<Option.Option<V>> =>
    Effect.gen(function*() {
      const currentMap = yield* TxRef.get(self.ref)
      const currentValue = HashMap.get(currentMap, key)
      if (Option.isSome(currentValue)) {
        const newValue = f(currentValue.value)
        yield* TxRef.set(self.ref, HashMap.set(currentMap, key, newValue))
        return currentValue
      }
      return Option.none()
    }).pipe(Effect.tx)
)