Hyperlinkv0.8.0-beta.28

MutableHashMap

MutableHashMap.modifyAtconsteffect/MutableHashMap.ts:630
<K, V>(key: K, f: (value: Option.Option<V>) => Option.Option<V>): (
  self: MutableHashMap<K, V>
) => MutableHashMap<K, V>
<K, V>(
  self: MutableHashMap<K, V>,
  key: K,
  f: (value: Option.Option<V>) => Option.Option<V>
): MutableHashMap<K, V>

Updates or removes the specified key using a function from the current optional value to the next optional value.

When to use

Use to decide whether to insert, update, or remove a key based on its current optional value.

Example (Updating or removing a key)

import { MutableHashMap, Option } from "effect"

const map = MutableHashMap.make(["count", 5])

// Update existing key
MutableHashMap.modifyAt(
  map,
  "count",
  (option) => Option.map(option, (n) => n * 2)
)
console.log(MutableHashMap.get(map, "count")) // Some(10)

// Add new key
MutableHashMap.modifyAt(
  map,
  "new",
  (option) => Option.isNone(option) ? Option.some(42) : option
)
console.log(MutableHashMap.get(map, "new")) // Some(42)

// Remove key by returning None
MutableHashMap.modifyAt(map, "count", () => Option.none())
console.log(MutableHashMap.has(map, "count")) // false

// Conditional update
MutableHashMap.modifyAt(
  map,
  "new",
  (option) => Option.filter(option, (n) => n > 50) // Remove if <= 50
)
console.log(MutableHashMap.has(map, "new")) // false (42 <= 50)
export const modifyAt: {
  <K, V>(key: K, f: (value: Option.Option<V>) => Option.Option<V>): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>
  <K, V>(self: MutableHashMap<K, V>, key: K, f: (value: Option.Option<V>) => Option.Option<V>): MutableHashMap<K, V>
} = dual<
  <K, V>(
    key: K,
    f: (value: Option.Option<V>) => Option.Option<V>
  ) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,
  <K, V>(
    self: MutableHashMap<K, V>,
    key: K,
    f: (value: Option.Option<V>) => Option.Option<V>
  ) => MutableHashMap<K, V>
>(3, (self, key, f) => {
  const current = get(self, key)
  const result = f(current)
  if (Option.isNone(result)) {
    if (Option.isSome(current)) {
      remove(self, key)
    }
    return self
  }
  set(self, key, result.value)
  return self
})