Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MutableHashMap.ts

871 lines24.1 KB

1/**
2 * `MutableHashMap` is an in-place key-value map with fast lookup, insertion,
3 * removal, clearing, and iteration. It combines a native `Map` for ordinary
4 * JavaScript keys with hash buckets for keys that implement Effect `Equal` /
5 * `Hash`, so callers can mix referential and structural lookup in the same
6 * collection.
7 *
8 * **Mental model**
9 *
10 * - `MutableHashMap<K, V>` stores entries on a single mutable map instance
11 * - {@link set}, {@link remove}, and {@link clear} mutate that instance and
12 * return it for convenient piping
13 * - Keys that implement `Equal` / `Hash` are matched structurally through hash
14 * buckets; other keys use JavaScript map semantics
15 * - The map is iterable as `[key, value]` pairs and reports size in O(1)
16 *
17 * **Common tasks**
18 *
19 * - Create maps: {@link empty}, {@link make}, {@link fromIterable}
20 * - Read entries: {@link get}, {@link has}, {@link size}
21 * - Mutate entries: {@link set}, {@link modify}, {@link remove}, {@link clear}
22 * - Narrow unknown values: {@link isMutableHashMap}
23 *
24 * **Gotchas**
25 *
26 * - This data structure is intentionally mutable; share it only when callers
27 * agree on ownership
28 * - Mutating a structural key after insertion can make future lookups fail if
29 * its equality or hash changes
30 * - Iteration follows the underlying storage order and should not be used as a
31 * sorting guarantee
32 *
33 * **Performance**
34 *
35 * - Lookup, insertion, removal, clearing, and size are O(1) on average
36 * - Hash collisions can make key lookup and removal O(n)
37 * - Iteration is O(n)
38 *
39 * @since 2.0.0
40 */
41import type { NonEmptyArray } from "./Array.ts"
42import * as Equal from "./Equal.ts"
43import { format } from "./Formatter.ts"
44import { dual } from "./Function.ts"
45import * as Hash from "./Hash.ts"
46import { type Inspectable, NodeInspectSymbol, toJson } from "./Inspectable.ts"
47import * as Option from "./Option.ts"
48import type { Pipeable } from "./Pipeable.ts"
49import { pipeArguments } from "./Pipeable.ts"
50import { hasProperty } from "./Predicate.ts"
51​
52const TypeId = "~effect/collections/MutableHashMap"
53​
54/**
55 * A mutable hash map that stores key-value pairs and supports both referential
56 * and Effect structural equality.
57 *
58 * **When to use**
59 *
60 * Use as a mutable key-value map when in-place updates are acceptable and keys
61 * may rely on Effect structural equality.
62 *
63 * **Details**
64 *
65 * Operations mutate the map in place. Keys that implement `Equal` / `Hash` can
66 * be looked up structurally; other keys use normal JavaScript reference or
67 * primitive equality.
68 *
69 * **Example** (Using a mutable hash map)
70 *
71 * ```ts
72 * import { MutableHashMap } from "effect"
73 *
74 * // Create a mutable hash map with string keys and number values
75 * const map: MutableHashMap.MutableHashMap<string, number> = MutableHashMap
76 * .empty()
77 *
78 * // Add some data
79 * MutableHashMap.set(map, "count", 42)
80 * MutableHashMap.set(map, "total", 100)
81 *
82 * // Use as iterable
83 * for (const [key, value] of map) {
84 * console.log(`${key}: ${value}`)
85 * }
86 * // Output:
87 * // count: 42
88 * // total: 100
89 *
90 * // Convert to array
91 * const entries = Array.from(map)
92 * console.log(entries) // [["count", 42], ["total", 100]]
93 * ```
94 *
95 * @see {@link empty} for creating an empty mutable hash map
96 * @see {@link get} for reading values by key
97 * @see {@link set} for mutating entries by key
98 *
99 * @category models
100 * @since 2.0.0
101 */
102export interface MutableHashMap<out K, out V> extends Iterable<[K, V]>, Pipeable, Inspectable {
103 readonly [TypeId]: typeof TypeId
104 readonly backing: Map<K, V>
105 readonly buckets: Map<number, NonEmptyArray<K>>
107​
108/**
109 * Checks whether the specified value is a `MutableHashMap`, `false` otherwise.
110 *
111 * **When to use**
112 *
113 * Use to narrow an unknown value before treating it as a mutable hash map.
114 *
115 * **Details**
116 *
117 * The check looks for the `MutableHashMap` runtime marker.
118 *
119 * **Gotchas**
120 *
121 * The check does not validate the key or value types carried by the map.
122 *
123 * @see {@link MutableHashMap} for the mutable hash map interface
124 *
125 * @category refinements
126 * @since 4.0.0
127 */
128export const isMutableHashMap = <K, V>(value: unknown): value is MutableHashMap<K, V> => hasProperty(value, TypeId)
129​
130const MutableHashMapProto: Omit<MutableHashMap<unknown, unknown>, "backing" | "buckets" | "bucketsSize"> = {
131 [TypeId]: TypeId,
132 [Symbol.iterator](this: MutableHashMap<unknown, unknown>): Iterator<[unknown, unknown]> {
133 return this.backing[Symbol.iterator]()
134 },
135 toString() {
136 return `MutableHashMap(${format(Array.from(this))})`
137 },
138 toJSON() {
139 return {
140 _id: "MutableHashMap",
141 values: toJson(Array.from(this))
142 }
143 },
144 [NodeInspectSymbol]() {
145 return this.toJSON()
146 },
147 pipe() {
148 return pipeArguments(this, arguments)
149 }
151​
152/**
153 * Creates an empty MutableHashMap.
154 *
155 * **When to use**
156 *
157 * Use to create a fresh mutable map before adding entries over time.
158 *
159 * **Details**
160 *
161 * Each call returns a new empty map instance.
162 *
163 * **Example** (Creating an empty map)
164 *
165 * ```ts
166 * import { MutableHashMap } from "effect"
167 *
168 * const map = MutableHashMap.empty<string, number>()
169 *
170 * // Add some entries
171 * MutableHashMap.set(map, "key1", 42)
172 * MutableHashMap.set(map, "key2", 100)
173 *
174 * console.log(MutableHashMap.size(map)) // 2
175 * ```
176 *
177 * @see {@link make} for creating a map from explicit entries
178 * @see {@link fromIterable} for creating a map from an iterable of entries
179 *
180 * @category constructors
181 * @since 2.0.0
182 */
183export const empty = <K, V>(): MutableHashMap<K, V> => {
184 const self = Object.create(MutableHashMapProto)
185 self.backing = new Map()
186 self.buckets = new Map()
187 return self
189​
190/**
191 * Creates a MutableHashMap from a variable number of key-value pairs.
192 *
193 * **When to use**
194 *
195 * Use to create a mutable hash map from explicit entries known at the call site.
196 *
197 * **Example** (Creating a map from entries)
198 *
199 * ```ts
200 * import { MutableHashMap } from "effect"
201 *
202 * const map = MutableHashMap.make(
203 * ["key1", 42],
204 * ["key2", 100],
205 * ["key3", 200]
206 * )
207 *
208 * console.log(MutableHashMap.get(map, "key1")) // Some(42)
209 * console.log(MutableHashMap.size(map)) // 3
210 * ```
211 *
212 * @see {@link empty} for creating an empty map
213 * @see {@link fromIterable} for creating a map from an iterable of entries
214 *
215 * @category constructors
216 * @since 2.0.0
217 */
218export const make: <Entries extends Array<readonly [any, any]>>(
219 ...entries: Entries
220) => MutableHashMap<
221 Entries[number] extends readonly [infer K, any] ? K : never,
222 Entries[number] extends readonly [any, infer V] ? V : never
223> = (...entries) => fromIterable(entries)
224​
225/**
226 * Creates a MutableHashMap from an iterable collection of key-value pairs.
227 *
228 * **When to use**
229 *
230 * Use to create a mutable hash map from an existing iterable of entries.
231 *
232 * **Example** (Creating a map from an iterable)
233 *
234 * ```ts
235 * import { MutableHashMap } from "effect"
236 *
237 * const entries = [
238 * ["apple", 1],
239 * ["banana", 2],
240 * ["cherry", 3]
241 * ] as const
242 *
243 * const map = MutableHashMap.fromIterable(entries)
244 *
245 * console.log(MutableHashMap.get(map, "banana")) // Some(2)
246 * console.log(MutableHashMap.size(map)) // 3
247 *
248 * // Works with any iterable
249 * const fromMap = MutableHashMap.fromIterable(new Map([["x", 10], ["y", 20]]))
250 * console.log(MutableHashMap.get(fromMap, "x")) // Some(10)
251 * ```
252 *
253 * @see {@link make} for creating a map from explicit entries
254 * @see {@link empty} for creating an empty map
255 *
256 * @category constructors
257 * @since 2.0.0
258 */
259export const fromIterable = <K, V>(entries: Iterable<readonly [K, V]>): MutableHashMap<K, V> => {
260 const self = empty<K, V>()
261 for (const [key, value] of entries) {
262 set(self, key, value)
263 }
264 return self
266​
267/**
268 * Looks up a key in the `MutableHashMap` safely.
269 *
270 * **When to use**
271 *
272 * Use to safely read the value for a key as an `Option`.
273 *
274 * **Details**
275 *
276 * Returns `Some(value)` when an equal key is present and `None` when the key is
277 * absent.
278 *
279 * **Example** (Getting a value)
280 *
281 * ```ts
282 * import { MutableHashMap } from "effect"
283 *
284 * const map = MutableHashMap.make(["key1", 42], ["key2", 100])
285 *
286 * console.log(MutableHashMap.get(map, "key1")) // Some(42)
287 * console.log(MutableHashMap.get(map, "key3")) // None
288 *
289 * // Pipe-able version
290 * const getValue = MutableHashMap.get("key1")
291 * console.log(getValue(map)) // Some(42)
292 * ```
293 *
294 * @see {@link has} for checking only whether a key is present
295 * @see {@link set} for inserting or replacing a value by key
296 *
297 * @category elements
298 * @since 2.0.0
299 */
300export const get: {
301 <K>(key: K): <V>(self: MutableHashMap<K, V>) => Option.Option<V>
302 <K, V>(self: MutableHashMap<K, V>, key: K): Option.Option<V>
303} = dual<
304 <K>(key: K) => <V>(self: MutableHashMap<K, V>) => Option.Option<V>,
305 <K, V>(self: MutableHashMap<K, V>, key: K) => Option.Option<V>
306>(2, <K, V>(self: MutableHashMap<K, V>, key: K): Option.Option<V> => {
307 if (self.backing.has(key)) {
308 return Option.some(self.backing.get(key)!)
309 } else if (isSimpleKey(key)) {
310 return Option.none()
311 }
312 const refKey = referentialKeysCache.get(self)
313 if (refKey !== undefined) {
314 return self.backing.has(refKey) ? Option.some(self.backing.get(refKey)!) : Option.none()
315 }
316 const hash = Hash.hash(key)
317 const bucket = self.buckets.get(hash)
318 if (bucket === undefined) {
319 return Option.none()
320 }
321 return getFromBucket(self, bucket, key)
322})
323​
324const referentialKeysCache = new WeakMap<any, any>()
325const isSimpleKey = (u: unknown): boolean => typeof u !== "object" && typeof u !== "function"
326​
327/**
328 * Returns an iterable over the keys in the `MutableHashMap`.
329 *
330 * **When to use**
331 *
332 * Use to iterate over the keys currently stored in a mutable hash map.
333 *
334 * **Example** (Reading keys)
335 *
336 * ```ts
337 * import { MutableHashMap } from "effect"
338 *
339 * const map = MutableHashMap.make(
340 * ["apple", 1],
341 * ["banana", 2],
342 * ["cherry", 3]
343 * )
344 *
345 * const allKeys = Array.from(MutableHashMap.keys(map))
346 * console.log(allKeys) // ["apple", "banana", "cherry"]
347 *
348 * // Useful for iteration or validation
349 * const hasRequiredKeys = allKeys.includes("apple") && allKeys.includes("banana")
350 * ```
351 *
352 * @see {@link values} for iterating over stored values
353 * @see {@link has} for checking one key without iterating
354 *
355 * @category elements
356 * @since 3.8.0
357 */
358export const keys = <K, V>(self: MutableHashMap<K, V>): Iterable<K> => self.backing.keys()
359​
360/**
361 * Returns an iterable over the values in the `MutableHashMap`.
362 *
363 * **When to use**
364 *
365 * Use to iterate over the values currently stored in a mutable hash map.
366 *
367 * **Example** (Reading values)
368 *
369 * ```ts
370 * import { MutableHashMap } from "effect"
371 *
372 * const map = MutableHashMap.make(
373 * ["apple", 1],
374 * ["banana", 2],
375 * ["cherry", 3]
376 * )
377 *
378 * const allValues = Array.from(MutableHashMap.values(map))
379 * console.log(allValues) // [1, 2, 3]
380 *
381 * // Useful for calculations
382 * const total = allValues.reduce((sum, value) => sum + value, 0)
383 * console.log(total) // 6
384 *
385 * // Filter values
386 * const largeValues = allValues.filter((value) => value > 1)
387 * console.log(largeValues) // [2, 3]
388 * ```
389 *
390 * @see {@link keys} for iterating over stored keys
391 *
392 * @category elements
393 * @since 3.8.0
394 */
395export const values = <K, V>(self: MutableHashMap<K, V>): Iterable<V> => self.backing.values()
396​
397const getFromBucket = <K, V>(
398 self: MutableHashMap<K, V>,
399 bucket: NonEmptyArray<K>,
400 key: K
401): Option.Option<V> => {
402 for (let i = 0, len = bucket.length; i < len; i++) {
403 if (Equal.equals(key, bucket[i])) {
404 const refKey = bucket[i]
405 referentialKeysCache.set(key, refKey)
406 return Option.some(self.backing.get(refKey)!)
407 }
408 }
409 return Option.none()
411​
412/**
413 * Checks whether the MutableHashMap contains the specified key.
414 *
415 * **When to use**
416 *
417 * Use to test whether a key is present without reading its value.
418 *
419 * **Example** (Checking for a key)
420 *
421 * ```ts
422 * import { MutableHashMap } from "effect"
423 *
424 * const map = MutableHashMap.make(["key1", 42], ["key2", 100])
425 *
426 * console.log(MutableHashMap.has(map, "key1")) // true
427 * console.log(MutableHashMap.has(map, "key3")) // false
428 *
429 * // Pipe-able version
430 * const hasKey = MutableHashMap.has("key1")
431 * console.log(hasKey(map)) // true
432 * ```
433 *
434 * @see {@link get} for reading the value as an `Option`
435 *
436 * @category elements
437 * @since 2.0.0
438 */
439export const has: {
440 <K>(key: K): <V>(self: MutableHashMap<K, V>) => boolean
441 <K, V>(self: MutableHashMap<K, V>, key: K): boolean
442} = dual<
443 <K>(key: K) => <V>(self: MutableHashMap<K, V>) => boolean,
444 <K, V>(self: MutableHashMap<K, V>, key: K) => boolean
445>(2, (self, key) => Option.isSome(get(self, key)))
446​
447/**
448 * Sets a key-value pair in the MutableHashMap, mutating the map in place.
449 * If the key already exists, its value is updated.
450 *
451 * **When to use**
452 *
453 * Use to insert a new entry or replace an existing entry in place.
454 *
455 * **Example** (Setting key-value pairs)
456 *
457 * ```ts
458 * import { MutableHashMap } from "effect"
459 *
460 * const map = MutableHashMap.empty<string, number>()
461 *
462 * // Add new entries
463 * MutableHashMap.set(map, "key1", 42)
464 * MutableHashMap.set(map, "key2", 100)
465 *
466 * console.log(MutableHashMap.get(map, "key1")) // Some(42)
467 * console.log(MutableHashMap.size(map)) // 2
468 *
469 * // Update existing entry
470 * MutableHashMap.set(map, "key1", 999)
471 * console.log(MutableHashMap.get(map, "key1")) // Some(999)
472 *
473 * // Pipe-able version
474 * const setKey = MutableHashMap.set("key3", 300)
475 * setKey(map)
476 * console.log(MutableHashMap.size(map)) // 3
477 * ```
478 *
479 * @see {@link modify} for updating an existing value with a function
480 * @see {@link modifyAt} for setting or removing based on the current optional value
481 * @see {@link remove} for deleting an entry by key
482 *
483 * @category mutations
484 * @since 2.0.0
485 */
486export const set: {
487 <K, V>(key: K, value: V): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>
488 <K, V>(self: MutableHashMap<K, V>, key: K, value: V): MutableHashMap<K, V>
489} = dual<
490 <K, V>(key: K, value: V) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,
491 <K, V>(self: MutableHashMap<K, V>, key: K, value: V) => MutableHashMap<K, V>
492>(3, <K, V>(self: MutableHashMap<K, V>, key: K, value: V) => {
493 if (self.backing.has(key) || isSimpleKey(key)) {
494 self.backing.set(key, value)
495 return self
496 }
497 let refKey = referentialKeysCache.get(self)
498 if (refKey !== undefined && self.backing.has(refKey)) {
499 self.backing.set(refKey, value)
500 return self
501 }
502​
503 const hash = Hash.hash(key)
504 const bucket = self.buckets.get(hash)
505 if (bucket === undefined) {
506 self.buckets.set(hash, [key])
507 self.backing.set(key, value)
508 return self
509 }
510​
511 refKey = getRefKey(bucket, key)
512 if (refKey === undefined) {
513 bucket.push(key)
514 refKey = key
515 }
516 self.backing.set(refKey, value)
517 return self
518})
519​
520const getRefKey = <K>(
521 bucket: NonEmptyArray<K>,
522 key: K
523) => {
524 for (let i = 0, len = bucket.length; i < len; i++) {
525 if (Equal.equals(key, bucket[i])) {
526 referentialKeysCache.set(key, bucket[i])
527 return bucket[i]
528 }
529 }
531​
532/**
533 * Updates the value of the specified key within the MutableHashMap if it exists.
534 * If the key doesn't exist, the map remains unchanged.
535 *
536 * **When to use**
537 *
538 * Use to transform an existing value in place without inserting missing keys.
539 *
540 * **Example** (Modifying existing values)
541 *
542 * ```ts
543 * import { MutableHashMap } from "effect"
544 *
545 * const map = MutableHashMap.make(["count", 5], ["total", 100])
546 *
547 * // Increment existing value
548 * MutableHashMap.modify(map, "count", (n) => n + 1)
549 * console.log(MutableHashMap.get(map, "count")) // Some(6)
550 *
551 * // Double existing value
552 * MutableHashMap.modify(map, "total", (n) => n * 2)
553 * console.log(MutableHashMap.get(map, "total")) // Some(200)
554 *
555 * // Try to modify non-existent key (no effect)
556 * MutableHashMap.modify(map, "missing", (n) => n + 1)
557 * console.log(MutableHashMap.has(map, "missing")) // false
558 *
559 * // Pipe-able version
560 * const increment = MutableHashMap.modify("count", (n: number) => n + 1)
561 * increment(map)
562 * ```
563 *
564 * @see {@link set} for inserting or replacing a value directly
565 * @see {@link modifyAt} for handling both missing and existing keys
566 *
567 * @category mutations
568 * @since 2.0.0
569 */
570export const modify: {
571 <K, V>(key: K, f: (v: V) => V): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>
572 <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V): MutableHashMap<K, V>
573} = dual<
574 <K, V>(key: K, f: (v: V) => V) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,
575 <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => MutableHashMap<K, V>
576>(3, <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => {
577 const hasKey = self.backing.has(key)
578 if (hasKey || isSimpleKey(key)) {
579 if (hasKey) {
580 self.backing.set(key, f(self.backing.get(key)!))
581 }
582 return self
583 }
584 let refKey = referentialKeysCache.get(self)
585 if (refKey !== undefined && self.backing.has(refKey)) {
586 self.backing.set(refKey, f(self.backing.get(refKey)!))
587 return self
588 }
589​
590 const hash = Hash.hash(key)
591 const bucket = self.buckets.get(hash)
592 if (bucket === undefined) {
593 return self
594 }
595​
596 refKey = getRefKey(bucket, key)
597 if (refKey === undefined) {
598 return self
599 }
600 self.backing.set(refKey, f(self.backing.get(refKey)!))
601 return self
602})
603​
604/**
605 * Updates or removes the specified key using a function from the current
606 * optional value to the next optional value.
607 *
608 * **When to use**
609 *
610 * Use to decide whether to insert, update, or remove a key based on its current
611 * optional value.
612 *
613 * **Example** (Updating or removing a key)
614 *
615 * ```ts
616 * import { MutableHashMap, Option } from "effect"
617 *
618 * const map = MutableHashMap.make(["count", 5])
619 *
620 * // Update existing key
621 * MutableHashMap.modifyAt(
622 * map,
623 * "count",
624 * (option) => Option.map(option, (n) => n * 2)
625 * )
626 * console.log(MutableHashMap.get(map, "count")) // Some(10)
627 *
628 * // Add new key
629 * MutableHashMap.modifyAt(
630 * map,
631 * "new",
632 * (option) => Option.isNone(option) ? Option.some(42) : option
633 * )
634 * console.log(MutableHashMap.get(map, "new")) // Some(42)
635 *
636 * // Remove key by returning None
637 * MutableHashMap.modifyAt(map, "count", () => Option.none())
638 * console.log(MutableHashMap.has(map, "count")) // false
639 *
640 * // Conditional update
641 * MutableHashMap.modifyAt(
642 * map,
643 * "new",
644 * (option) => Option.filter(option, (n) => n > 50) // Remove if <= 50
645 * )
646 * console.log(MutableHashMap.has(map, "new")) // false (42 <= 50)
647 * ```
648 *
649 * @see {@link modify} for updating only when the key already exists
650 * @see {@link set} for inserting or replacing directly
651 * @see {@link remove} for deleting directly
652 *
653 * @category mutations
654 * @since 2.0.0
655 */
656export const modifyAt: {
657 <K, V>(key: K, f: (value: Option.Option<V>) => Option.Option<V>): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>
658 <K, V>(self: MutableHashMap<K, V>, key: K, f: (value: Option.Option<V>) => Option.Option<V>): MutableHashMap<K, V>
659} = dual<
660 <K, V>(
661 key: K,
662 f: (value: Option.Option<V>) => Option.Option<V>
663 ) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,
664 <K, V>(
665 self: MutableHashMap<K, V>,
666 key: K,
667 f: (value: Option.Option<V>) => Option.Option<V>
668 ) => MutableHashMap<K, V>
669>(3, (self, key, f) => {
670 const current = get(self, key)
671 const result = f(current)
672 if (Option.isNone(result)) {
673 if (Option.isSome(current)) {
674 remove(self, key)
675 }
676 return self
677 }
678 set(self, key, result.value)
679 return self
680})
681​
682/**
683 * Removes the specified key from the MutableHashMap, mutating the map in place.
684 * If the key doesn't exist, the map remains unchanged.
685 *
686 * **When to use**
687 *
688 * Use to delete one key from a mutable hash map in place.
689 *
690 * **Example** (Removing a key)
691 *
692 * ```ts
693 * import { MutableHashMap } from "effect"
694 *
695 * const map = MutableHashMap.make(
696 * ["key1", 42],
697 * ["key2", 100],
698 * ["key3", 200]
699 * )
700 *
701 * console.log(MutableHashMap.size(map)) // 3
702 *
703 * // Remove existing key
704 * MutableHashMap.remove(map, "key2")
705 * console.log(MutableHashMap.size(map)) // 2
706 * console.log(MutableHashMap.has(map, "key2")) // false
707 *
708 * // Remove non-existent key (no effect)
709 * MutableHashMap.remove(map, "nonexistent")
710 * console.log(MutableHashMap.size(map)) // 2
711 *
712 * // Pipe-able version
713 * const removeKey = MutableHashMap.remove("key1")
714 * removeKey(map)
715 * console.log(MutableHashMap.size(map)) // 1
716 * ```
717 *
718 * @see {@link clear} for removing all entries
719 * @see {@link modifyAt} for conditionally removing based on the current value
720 *
721 * @category mutations
722 * @since 2.0.0
723 */
724export const remove: {
725 <K>(key: K): <V>(self: MutableHashMap<K, V>) => MutableHashMap<K, V>
726 <K, V>(self: MutableHashMap<K, V>, key: K): MutableHashMap<K, V>
727} = dual<
728 <K>(key: K) => <V>(self: MutableHashMap<K, V>) => MutableHashMap<K, V>,
729 <K, V>(self: MutableHashMap<K, V>, key: K) => MutableHashMap<K, V>
730>(2, <K, V>(self: MutableHashMap<K, V>, key_: K) => {
731 if (isSimpleKey(key_)) {
732 self.backing.delete(key_)
733 return self
734 }
735​
736 const key = referentialKeysCache.get(self) ?? key_
737 const hash = Hash.hash(key)
738 const bucket = self.buckets.get(hash)
739 if (bucket === undefined) {
740 return self
741 }
742 for (let i = 0, len = bucket.length; i < len; i++) {
743 const bkey = bucket[i]
744 if (bkey === key || Equal.equals(key, bkey)) {
745 self.backing.delete(bkey)
746 bucket.splice(i, 1)
747 break
748 }
749 }
750 if (bucket.length === 0) {
751 self.buckets.delete(hash)
752 }
753 return self
754})
755​
756/**
757 * Removes all key-value pairs from the MutableHashMap, mutating the map in place.
758 * The map becomes empty after this operation.
759 *
760 * **When to use**
761 *
762 * Use to empty a mutable hash map while keeping the same map instance.
763 *
764 * **Example** (Clearing all entries)
765 *
766 * ```ts
767 * import { MutableHashMap } from "effect"
768 *
769 * const map = MutableHashMap.make(
770 * ["key1", 42],
771 * ["key2", 100],
772 * ["key3", 200]
773 * )
774 *
775 * console.log(MutableHashMap.size(map)) // 3
776 *
777 * // Clear all entries
778 * MutableHashMap.clear(map)
779 *
780 * console.log(MutableHashMap.size(map)) // 0
781 * console.log(MutableHashMap.has(map, "key1")) // false
782 *
783 * // Can still add new entries after clearing
784 * MutableHashMap.set(map, "new", 999)
785 * console.log(MutableHashMap.size(map)) // 1
786 * ```
787 *
788 * @see {@link remove} for deleting one key
789 * @see {@link empty} for creating a fresh empty map
790 *
791 * @category mutations
792 * @since 2.0.0
793 */
794export const clear = <K, V>(self: MutableHashMap<K, V>) => {
795 self.backing.clear()
796 self.buckets.clear()
797 return self
799​
800/**
801 * Returns the number of key-value pairs in the MutableHashMap.
802 *
803 * **When to use**
804 *
805 * Use to read how many entries are currently stored in the mutable hash map.
806 *
807 * **Example** (Checking map size)
808 *
809 * ```ts
810 * import { MutableHashMap } from "effect"
811 *
812 * const map = MutableHashMap.empty<string, number>()
813 * console.log(MutableHashMap.size(map)) // 0
814 *
815 * MutableHashMap.set(map, "key1", 42)
816 * MutableHashMap.set(map, "key2", 100)
817 * console.log(MutableHashMap.size(map)) // 2
818 *
819 * MutableHashMap.remove(map, "key1")
820 * console.log(MutableHashMap.size(map)) // 1
821 *
822 * MutableHashMap.clear(map)
823 * console.log(MutableHashMap.size(map)) // 0
824 * ```
825 *
826 * @see {@link isEmpty} for checking whether the map has no entries
827 *
828 * @category elements
829 * @since 2.0.0
830 */
831export const size = <K, V>(self: MutableHashMap<K, V>): number => self.backing.size
832​
833/**
834 * Returns `true` when the `MutableHashMap` contains no key-value pairs.
835 *
836 * **When to use**
837 *
838 * Use to branch on whether a mutable map currently has any entries.
839 *
840 * @see {@link size} for reading the exact number of entries
841 *
842 * @category predicates
843 * @since 2.0.0
844 */
845export const isEmpty = <K, V>(self: MutableHashMap<K, V>): boolean => self.backing.size === 0
846​
847/**
848 * Runs a callback for each key-value pair in the `MutableHashMap`.
849 *
850 * **When to use**
851 *
852 * Use to run a synchronous side-effecting callback for every key-value pair in
853 * an existing mutable map.
854 *
855 * **Details**
856 *
857 * Iteration follows the backing map's order. The callback receives the value
858 * first and the key second, matching `Map.prototype.forEach`.
859 *
860 * @see {@link keys} for iterating only keys
861 * @see {@link values} for iterating only values
862 *
863 * @category traversing
864 * @since 2.0.0
865 */
866export const forEach: {
867 <K, V>(f: (value: V, key: K) => void): (self: MutableHashMap<K, V>) => void
868 <K, V>(self: MutableHashMap<K, V>, f: (value: V, key: K) => void): void
869} = dual(2, <K, V>(self: MutableHashMap<K, V>, f: (value: V, key: K) => void) => {
870 self.backing.forEach(f)
871})