Hyperlinkv0.8.0-beta.28

MutableHashMap

MutableHashMap.modifyconsteffect/MutableHashMap.ts:544
<K, V>(key: K, f: (v: V) => V): (
  self: MutableHashMap<K, V>
) => MutableHashMap<K, V>
<K, V>(
  self: MutableHashMap<K, V>,
  key: K,
  f: (v: V) => V
): MutableHashMap<K, V>

Updates the value of the specified key within the MutableHashMap if it exists. If the key doesn't exist, the map remains unchanged.

When to use

Use to transform an existing MutableHashMap value in place without inserting missing keys.

Example (Modifying existing values)

import { MutableHashMap } from "effect"

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

// Increment existing value
MutableHashMap.modify(map, "count", (n) => n + 1)
console.log(MutableHashMap.get(map, "count")) // Some(6)

// Double existing value
MutableHashMap.modify(map, "total", (n) => n * 2)
console.log(MutableHashMap.get(map, "total")) // Some(200)

// Try to modify non-existent key (no effect)
MutableHashMap.modify(map, "missing", (n) => n + 1)
console.log(MutableHashMap.has(map, "missing")) // false

// Pipe-able version
const increment = MutableHashMap.modify("count", (n: number) => n + 1)
increment(map)
mutationssetmodifyAt
export const modify: {
  <K, V>(key: K, f: (v: V) => V): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>
  <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V): MutableHashMap<K, V>
} = dual<
  <K, V>(key: K, f: (v: V) => V) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,
  <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => MutableHashMap<K, V>
>(3, <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => {
  const hasKey = self.backing.has(key)
  if (hasKey || isSimpleKey(key)) {
    if (hasKey) {
      self.backing.set(key, f(self.backing.get(key)!))
    }
    return self
  }
  let refKey = referentialKeysCache.get(self)
  if (refKey !== undefined && self.backing.has(refKey)) {
    self.backing.set(refKey, f(self.backing.get(refKey)!))
    return self
  }

  const hash = Hash.hash(key)
  const bucket = self.buckets.get(hash)
  if (bucket === undefined) {
    return self
  }

  refKey = getRefKey(bucket, key)
  if (refKey === undefined) {
    return self
  }
  self.backing.set(refKey, f(self.backing.get(refKey)!))
  return self
})