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

MutableHashMap.ts

824 lines22.5 KB

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