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