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

HashMap.ts

1,236 lines34.9 KB

1/**
2 * Stores key/value entries in an immutable hash map.
3 *
4 * A `HashMap<Key, Value>` hashes keys and resolves matches with Effect's
5 * structural equality rules. Lookup, insertion, removal, and transformation
6 * operations return new maps, while temporary mutation helpers support efficient
7 * batch updates. This module also includes constructors, iteration, conversion,
8 * mapping, filtering, and reducing helpers.
9 *
10 * @since 2.0.0
11 */
12​
13import type { Equal } from "./Equal.ts"
14import type { Inspectable } from "./Inspectable.ts"
15import * as internal from "./internal/hashMap.ts"
16import type { Option } from "./Option.ts"
17import type { Pipeable } from "./Pipeable.ts"
18import type { Result } from "./Result.ts"
19import type { NoInfer } from "./Types.ts"
20​
21const TypeId = internal.HashMapTypeId
22​
23/**
24 * A HashMap is an immutable key-value data structure that provides efficient lookup,
25 * insertion, and deletion operations. It uses a Hash Array Mapped Trie (HAMT) internally
26 * for structural sharing and optimal performance.
27 *
28 * **Example** (Using basic HashMap operations)
29 *
30 * ```ts
31 * import { HashMap } from "effect"
32 *
33 * // Create a HashMap
34 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
35 *
36 * // Access values
37 * const valueA = HashMap.get(map, "a") // Option.some(1)
38 * const valueD = HashMap.get(map, "d") // Option.none()
39 *
40 * // Check if key exists
41 * console.log(HashMap.has(map, "b")) // true
42 *
43 * // Add/update values (returns new HashMap)
44 * const updated = HashMap.set(map, "d", 4)
45 * console.log(HashMap.size(updated)) // 4
46 * ```
47 *
48 * @category models
49 * @since 2.0.0
50 */
51export interface HashMap<out Key, out Value> extends Iterable<[Key, Value]>, Equal, Pipeable, Inspectable {
52 readonly [TypeId]: typeof TypeId
54​
55/**
56 * The HashMap namespace contains type-level utilities and helper types
57 * for working with HashMap instances.
58 *
59 * **Example** (Extracting HashMap types)
60 *
61 * ```ts
62 * import { HashMap } from "effect"
63 *
64 * // Create a concrete HashMap for type extraction
65 * const inventory = HashMap.make(
66 * ["laptop", { quantity: 5, price: 999 }],
67 * ["mouse", { quantity: 20, price: 29 }]
68 * )
69 *
70 * // Extract types for reuse
71 * type ProductId = HashMap.HashMap.Key<typeof inventory> // string
72 * type Product = HashMap.HashMap.Value<typeof inventory> // { quantity: number, price: number }
73 * type InventoryEntry = HashMap.HashMap.Entry<typeof inventory> // [string, Product]
74 *
75 * // Use extracted types in functions
76 * const updateInventory = (id: ProductId, product: Product) =>
77 * HashMap.set(inventory, id, product)
78 *
79 * const processEntry = ([id, product]: InventoryEntry) =>
80 * `${id}: ${product.quantity} @ $${product.price}`
81 *
82 * // Example of extracted types in action
83 * const newProduct: Product = { quantity: 10, price: 199 }
84 * const updatedInventory = updateInventory("tablet", newProduct)
85 * ```
86 *
87 * @since 2.0.0
88 */
89export declare namespace HashMap {
90 /**
91 * A function that updates a value based on its current state.
92 * Takes an Option representing the current value and returns an Option
93 * representing the new value.
94 *
95 * **Example** (Updating values from Options)
96 *
97 * ```ts
98 * import { HashMap, Option } from "effect"
99 *
100 * const map = HashMap.make(["a", 1], ["b", 2])
101 *
102 * // Increment existing value or set to 1 if not present
103 * const updateFn = (option: Option.Option<number>) =>
104 * Option.isSome(option) ? Option.some(option.value + 1) : Option.some(1)
105 *
106 * const updated = HashMap.modifyAt(map, "a", updateFn)
107 * console.log(HashMap.get(updated, "a")) // Option.some(2)
108 * ```
109 *
110 * @category models
111 * @since 2.0.0
112 */
113 export type UpdateFn<V> = (option: Option<V>) => Option<V>
114​
115 /**
116 * This type-level utility extracts the key type `K` from a `HashMap<K, V>` type.
117 *
118 * **Example** (Extracting key types)
119 *
120 * ```ts
121 * import { HashMap } from "effect"
122 *
123 * // Create a HashMap to extract key type from
124 * const userMap = HashMap.make(
125 * ["alice", { name: "Alice", age: 30 }],
126 * ["bob", { name: "Bob", age: 25 }]
127 * )
128 *
129 * // Extract the key type (string)
130 * type UserKey = HashMap.HashMap.Key<typeof userMap>
131 *
132 * // Use the extracted type in functions
133 * const getUserById = (id: UserKey) => HashMap.get(userMap, id)
134 * console.log(getUserById("alice")) // Option.some({ name: "Alice", age: 30 })
135 * ```
136 *
137 * @category utility types
138 * @since 2.0.0
139 */
140 export type Key<T extends HashMap<any, any>> = [T] extends [HashMap<infer _K, infer _V>] ? _K : never
141​
142 /**
143 * This type-level utility extracts the value type `V` from a `HashMap<K, V>` type.
144 *
145 * **Example** (Extracting value types)
146 *
147 * ```ts
148 * import { HashMap } from "effect"
149 *
150 * // Create a HashMap with user data
151 * const userMap = HashMap.make(
152 * ["alice", { name: "Alice", age: 30, active: true }],
153 * ["bob", { name: "Bob", age: 25, active: false }]
154 * )
155 *
156 * // Extract the value type (User object)
157 * type User = HashMap.HashMap.Value<typeof userMap>
158 *
159 * // Use the extracted type for type-safe operations
160 * const processUser = (user: User) => {
161 * return user.active ? `${user.name} (active)` : `${user.name} (inactive)`
162 * }
163 *
164 * const alice = HashMap.get(userMap, "alice")
165 * // alice has type Option<User> thanks to type extraction
166 * ```
167 *
168 * @category utility types
169 * @since 2.0.0
170 */
171 export type Value<T extends HashMap<any, any>> = [T] extends [HashMap<infer _K, infer _V>] ? _V : never
172​
173 /**
174 * This type-level utility extracts the entry type `[K, V]` from a `HashMap<K, V>` type.
175 *
176 * **Example** (Extracting entry types)
177 *
178 * ```ts
179 * import { HashMap } from "effect"
180 *
181 * // Create a product catalog HashMap
182 * const catalog = HashMap.make(
183 * ["laptop", { price: 999, category: "electronics" }],
184 * ["book", { price: 29, category: "education" }]
185 * )
186 *
187 * // Extract the entry type [string, Product]
188 * type CatalogEntry = HashMap.HashMap.Entry<typeof catalog>
189 *
190 * // Use the extracted type for processing entries
191 * const processEntry = ([productId, product]: CatalogEntry) => {
192 * return `${productId}: $${product.price} (${product.category})`
193 * }
194 *
195 * // Convert to entries, process, and sort for deterministic output
196 * const descriptions = HashMap.toEntries(catalog).map(processEntry).sort()
197 * console.log(descriptions) // ["book: $29 (education)", "laptop: $999 (electronics)"]
198 * ```
199 *
200 * @category utility types
201 * @since 3.9.0
202 */
203 export type Entry<T extends HashMap<any, any>> = [Key<T>, Value<T>]
205​
206/**
207 * Checks whether a value is a HashMap.
208 *
209 * **Example** (Checking HashMap values)
210 *
211 * ```ts
212 * import { HashMap } from "effect"
213 *
214 * const map = HashMap.make(["a", 1], ["b", 2])
215 * const notMap = { a: 1 }
216 *
217 * console.log(HashMap.isHashMap(map)) // true
218 * console.log(HashMap.isHashMap(notMap)) // false
219 * console.log(HashMap.isHashMap(null)) // false
220 * ```
221 *
222 * @category refinements
223 * @since 2.0.0
224 */
225export const isHashMap: {
226 <K, V>(u: Iterable<readonly [K, V]>): u is HashMap<K, V>
227 (u: unknown): u is HashMap<unknown, unknown>
228} = internal.isHashMap
229​
230/**
231 * Creates a new empty `HashMap`.
232 *
233 * **Example** (Creating an empty HashMap)
234 *
235 * ```ts
236 * import { HashMap } from "effect"
237 *
238 * const map = HashMap.empty<string, number>()
239 * console.log(HashMap.isEmpty(map)) // true
240 * console.log(HashMap.size(map)) // 0
241 * ```
242 *
243 * @category constructors
244 * @since 2.0.0
245 */
246export const empty: <K = never, V = never>() => HashMap<K, V> = internal.empty
247​
248/**
249 * Constructs a new `HashMap` from an array of key/value pairs.
250 *
251 * **Example** (Creating a HashMap from entries)
252 *
253 * ```ts
254 * import { HashMap } from "effect"
255 *
256 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
257 * console.log(HashMap.size(map)) // 3
258 * console.log(HashMap.get(map, "b")) // Option.some(2)
259 * ```
260 *
261 * @category constructors
262 * @since 2.0.0
263 */
264export const make: <Entries extends ReadonlyArray<readonly [any, any]>>(
265 ...entries: Entries
266) => HashMap<
267 Entries[number] extends readonly [infer K, any] ? K : never,
268 Entries[number] extends readonly [any, infer V] ? V : never
269> = internal.make
270​
271/**
272 * Creates a new `HashMap` from an iterable collection of key/value pairs.
273 *
274 * **Example** (Creating a HashMap from an iterable)
275 *
276 * ```ts
277 * import { HashMap } from "effect"
278 *
279 * const entries = [["a", 1], ["b", 2], ["c", 3]] as const
280 * const map = HashMap.fromIterable(entries)
281 * console.log(HashMap.size(map)) // 3
282 * console.log(HashMap.get(map, "a")) // Option.some(1)
283 * ```
284 *
285 * @category constructors
286 * @since 2.0.0
287 */
288export const fromIterable: <K, V>(entries: Iterable<readonly [K, V]>) => HashMap<K, V> = internal.fromIterable
289​
290/**
291 * Checks whether the `HashMap` contains no entries.
292 *
293 * **Example** (Checking for empty HashMaps)
294 *
295 * ```ts
296 * import { HashMap } from "effect"
297 *
298 * const emptyMap = HashMap.empty<string, number>()
299 * const nonEmptyMap = HashMap.make(["a", 1])
300 *
301 * console.log(HashMap.isEmpty(emptyMap)) // true
302 * console.log(HashMap.isEmpty(nonEmptyMap)) // false
303 * ```
304 *
305 * @category elements
306 * @since 2.0.0
307 */
308export const isEmpty: <K, V>(self: HashMap<K, V>) => boolean = internal.isEmpty
309​
310/**
311 * Looks up the value for the specified key in the `HashMap` safely using the
312 * internal hashing function.
313 *
314 * **Example** (Looking up values)
315 *
316 * ```ts
317 * import { HashMap } from "effect"
318 *
319 * const map = HashMap.make(["a", 1], ["b", 2])
320 *
321 * console.log(HashMap.get(map, "a")) // Option.some(1)
322 * console.log(HashMap.get(map, "c")) // Option.none()
323 *
324 * // Using pipe syntax
325 * const value = HashMap.get("b")(map)
326 * console.log(value) // Option.some(2)
327 * ```
328 *
329 * @category elements
330 * @since 2.0.0
331 */
332export const get: {
333 <K1 extends K, K>(key: K1): <V>(self: HashMap<K, V>) => Option<V>
334 <K1 extends K, K, V>(self: HashMap<K, V>, key: K1): Option<V>
335} = internal.get
336​
337/**
338 * Looks up the value for the specified key in the `HashMap` safely using a custom hash.
339 *
340 * **Example** (Looking up values with a hash)
341 *
342 * ```ts
343 * import { Hash, HashMap } from "effect"
344 *
345 * // Useful when implementing custom equality for complex keys
346 * const userMap = HashMap.make(
347 * ["user123", { name: "Alice", role: "admin" }],
348 * ["user456", { name: "Bob", role: "user" }]
349 * )
350 *
351 * // Use precomputed hash for performance in hot paths
352 * const userId = "user123"
353 * const precomputedHash = Hash.string(userId)
354 *
355 * // Lookup with custom hash (e.g., cached hash value)
356 * const user = HashMap.getHash(userMap, userId, precomputedHash)
357 * console.log(user) // Option.some({ name: "Alice", role: "admin" })
358 *
359 * // This avoids recomputing the hash when you already have it
360 * const notFound = HashMap.getHash(userMap, "user999", Hash.string("user999"))
361 * console.log(notFound) // Option.none()
362 * ```
363 *
364 * @category elements
365 * @since 2.0.0
366 */
367export const getHash: {
368 <K1 extends K, K>(key: K1, hash: number): <V>(self: HashMap<K, V>) => Option<V>
369 <K1 extends K, K, V>(self: HashMap<K, V>, key: K1, hash: number): Option<V>
370} = internal.getHash
371​
372/**
373 * Looks up the value for the specified key in the `HashMap` unsafely using the
374 * internal hashing function.
375 *
376 * **When to use**
377 *
378 * Use when reading from a `HashMap` by a key known to exist, and throwing is an
379 * acceptable programming error for a missing key.
380 *
381 * **Gotchas**
382 *
383 * This function throws an error if the key is not found. Use `HashMap.get` for
384 * safe access that returns `Option`.
385 *
386 * **Example** (Unsafely looking up values)
387 *
388 * ```ts
389 * import { HashMap, Option } from "effect"
390 *
391 * const config = HashMap.make(
392 * ["api_url", "https://api.example.com"],
393 * ["timeout", "5000"],
394 * ["retries", "3"]
395 * )
396 *
397 * // Safe: use when you're certain the key exists
398 * const apiUrl = HashMap.getUnsafe(config, "api_url") // "https://api.example.com"
399 * console.log(`Connecting to: ${apiUrl}`)
400 *
401 * // Preferred: use get() for uncertain keys
402 * const dbUrl = HashMap.get(config, "db_url") // Option.none()
403 * if (Option.isSome(dbUrl)) {
404 * console.log(`Database: ${dbUrl.value}`)
405 * }
406 *
407 * // This would throw: HashMap.getUnsafe(config, "db_url")
408 * // Error: "HashMap.getUnsafe: key not found"
409 * ```
410 *
411 * @category unsafe
412 * @since 4.0.0
413 */
414export const getUnsafe: {
415 <K1 extends K, K>(key: K1): <V>(self: HashMap<K, V>) => V
416 <K1 extends K, K, V>(self: HashMap<K, V>, key: K1): V
417} = internal.getUnsafe
418​
419/**
420 * Checks whether the specified key has an entry in the `HashMap`.
421 *
422 * **Example** (Checking for keys)
423 *
424 * ```ts
425 * import { HashMap } from "effect"
426 *
427 * const map = HashMap.make(["a", 1], ["b", 2])
428 *
429 * console.log(HashMap.has(map, "a")) // true
430 * console.log(HashMap.has(map, "c")) // false
431 *
432 * // Using pipe syntax
433 * const hasB = HashMap.has("b")(map)
434 * console.log(hasB) // true
435 * ```
436 *
437 * @category elements
438 * @since 2.0.0
439 */
440export const has: {
441 <K1 extends K, K>(key: K1): <K, V>(self: HashMap<K, V>) => boolean
442 <K1 extends K, K, V>(self: HashMap<K, V>, key: K1): boolean
443} = internal.has
444​
445/**
446 * Checks whether the specified key has an entry in the `HashMap` using a custom
447 * hash.
448 *
449 * **Example** (Checking keys with a hash)
450 *
451 * ```ts
452 * import { Hash, HashMap } from "effect"
453 *
454 * // Create a map with case-sensitive keys
455 * const userMap = HashMap.make(
456 * ["Admin", { role: "administrator" }],
457 * ["User", { role: "standard" }]
458 * )
459 *
460 * // Check with exact hash
461 * const exactHash = Hash.string("Admin")
462 * console.log(HashMap.hasHash(userMap, "Admin", exactHash)) // true
463 *
464 * // A matching hash does not override key equality
465 * console.log(HashMap.hasHash(userMap, "admin", exactHash)) // false
466 *
467 * // A different hash also cannot find the existing key
468 * const lowercaseHash = Hash.string("admin")
469 * console.log(HashMap.hasHash(userMap, "Admin", lowercaseHash)) // false
470 * ```
471 *
472 * @category elements
473 * @since 2.0.0
474 */
475export const hasHash: {
476 <K1 extends K, K>(key: K1, hash: number): <V>(self: HashMap<K, V>) => boolean
477 <K1 extends K, K, V>(self: HashMap<K, V>, key: K1, hash: number): boolean
478} = internal.hasHash
479​
480/**
481 * Checks whether an element matching the given predicate exists in the given `HashMap`.
482 *
483 * **Example** (Checking entries by predicate)
484 *
485 * ```ts
486 * import { HashMap } from "effect"
487 *
488 * const hm = HashMap.make([1, "a"])
489 * HashMap.hasBy(hm, (value, key) => value === "a" && key === 1) // -> true
490 * HashMap.hasBy(hm, (value) => value === "b") // -> false
491 * ```
492 *
493 * @category elements
494 * @since 3.16.0
495 */
496export const hasBy: {
497 <K, V>(predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean): (self: HashMap<K, V>) => boolean
498 <K, V>(self: HashMap<K, V>, predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean): boolean
499} = internal.hasBy
500​
501/**
502 * Sets the specified key to the specified value using the internal hashing
503 * function.
504 *
505 * **Example** (Setting a value)
506 *
507 * ```ts
508 * import { HashMap } from "effect"
509 *
510 * const map1 = HashMap.make(["a", 1])
511 * const map2 = HashMap.set(map1, "b", 2)
512 *
513 * console.log(HashMap.size(map2)) // 2
514 * console.log(HashMap.get(map2, "b")) // Option.some(2)
515 *
516 * // Original map is unchanged
517 * console.log(HashMap.size(map1)) // 1
518 * ```
519 *
520 * @category transforming
521 * @since 2.0.0
522 */
523export const set: {
524 <K, V>(key: K, value: V): (self: HashMap<K, V>) => HashMap<K, V>
525 <K, V>(self: HashMap<K, V>, key: K, value: V): HashMap<K, V>
526} = internal.set
527​
528/**
529 * Returns an `IterableIterator` of the keys within the `HashMap`.
530 *
531 * **Example** (Iterating keys)
532 *
533 * ```ts
534 * import { HashMap } from "effect"
535 *
536 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
537 * const keys = Array.from(HashMap.keys(map))
538 * console.log(keys.sort()) // ["a", "b", "c"]
539 * ```
540 *
541 * @category getters
542 * @since 2.0.0
543 */
544export const keys: <K, V>(self: HashMap<K, V>) => IterableIterator<K> = internal.keys
545​
546/**
547 * Returns an `IterableIterator` of the values within the `HashMap`.
548 *
549 * **Example** (Iterating values)
550 *
551 * ```ts
552 * import { HashMap } from "effect"
553 *
554 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
555 * const values = Array.from(HashMap.values(map))
556 * console.log(values.sort()) // [1, 2, 3]
557 * ```
558 *
559 * @category getters
560 * @since 2.0.0
561 */
562export const values: <K, V>(self: HashMap<K, V>) => IterableIterator<V> = internal.values
563​
564/**
565 * Returns an `Array` of the values within the `HashMap`.
566 *
567 * **Example** (Converting values to an array)
568 *
569 * ```ts
570 * import { HashMap } from "effect"
571 *
572 * const employees = HashMap.make(
573 * ["alice", { department: "engineering", salary: 90000 }],
574 * ["bob", { department: "marketing", salary: 75000 }],
575 * ["charlie", { department: "engineering", salary: 95000 }]
576 * )
577 *
578 * // Extract all employee records
579 * const allEmployees = HashMap.toValues(employees)
580 * console.log(allEmployees.length) // 3
581 *
582 * // Calculate total salary
583 * const totalSalary = allEmployees.reduce((sum, emp) => sum + emp.salary, 0)
584 * console.log(totalSalary) // 260000
585 *
586 * // Filter by department
587 * const engineers = allEmployees.filter((emp) => emp.department === "engineering")
588 * console.log(engineers.length) // 2
589 * ```
590 *
591 * @category getters
592 * @since 3.13.0
593 */
594export const toValues = <K, V>(self: HashMap<K, V>): Array<V> => Array.from(values(self))
595​
596/**
597 * Returns an `IterableIterator` of the entries within the `HashMap`.
598 *
599 * **Example** (Iterating entries)
600 *
601 * ```ts
602 * import { HashMap } from "effect"
603 *
604 * // Create a configuration map
605 * const config = HashMap.make(
606 * ["database.host", "localhost"],
607 * ["database.port", "5432"],
608 * ["cache.enabled", "true"]
609 * )
610 *
611 * // Sort the derived array for deterministic output
612 * const settings = Array.from(HashMap.entries(config))
613 * .sort(([left], [right]) => left.localeCompare(right))
614 * .map(([key, value]) => `Setting ${key} = ${value}`)
615 *
616 * console.log(settings)
617 * // ["Setting cache.enabled = true", "Setting database.host = localhost", "Setting database.port = 5432"]
618 *
619 * // Convert to array when you need all entries at once
620 * const allEntries = Array.from(HashMap.entries(config))
621 * console.log(allEntries.length) // 3
622 * ```
623 *
624 * @category getters
625 * @since 2.0.0
626 */
627export const entries: <K, V>(self: HashMap<K, V>) => IterableIterator<[K, V]> = internal.entries
628​
629/**
630 * Returns an `Array<[K, V]>` of the entries within the `HashMap`.
631 *
632 * **Example** (Converting entries to an array)
633 *
634 * ```ts
635 * import { HashMap } from "effect"
636 *
637 * const gameScores = HashMap.make(
638 * ["alice", 1250],
639 * ["bob", 980],
640 * ["charlie", 1100]
641 * )
642 *
643 * // Convert to entries for processing
644 * const scoreEntries = HashMap.toEntries(gameScores)
645 *
646 * // Sort by score (descending)
647 * const leaderboard = scoreEntries
648 * .sort(([, a], [, b]) => b - a)
649 * .map(([player, score], rank) => `${rank + 1}. ${player}: ${score}`)
650 *
651 * console.log(leaderboard)
652 * // ["1. alice: 1250", "2. charlie: 1100", "3. bob: 980"]
653 *
654 * // Convert back to HashMap if needed
655 * const sortedMap = HashMap.fromIterable(scoreEntries)
656 * ```
657 *
658 * @category getters
659 * @since 2.0.0
660 */
661export const toEntries = <K, V>(self: HashMap<K, V>): Array<[K, V]> => Array.from(entries(self))
662​
663/**
664 * Returns the number of entries within the `HashMap`.
665 *
666 * **Example** (Getting the size)
667 *
668 * ```ts
669 * import { HashMap } from "effect"
670 *
671 * const emptyMap = HashMap.empty<string, number>()
672 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
673 *
674 * console.log(HashMap.size(emptyMap)) // 0
675 * console.log(HashMap.size(map)) // 3
676 * ```
677 *
678 * @category getters
679 * @since 2.0.0
680 */
681export const size: <K, V>(self: HashMap<K, V>) => number = internal.size
682​
683/**
684 * Creates a transient mutable `HashMap` for efficient batched updates.
685 *
686 * **Details**
687 *
688 * Apply updates to the returned map, then call `endMutation` to finish the
689 * mutation window and use the result as an immutable `HashMap`.
690 *
691 * **Example** (Beginning batch mutation)
692 *
693 * ```ts
694 * import { HashMap } from "effect"
695 *
696 * const map = HashMap.make(["a", 1])
697 *
698 * // Begin mutation for efficient batch operations
699 * const mutable = HashMap.beginMutation(map)
700 *
701 * // Multiple operations are now more efficient
702 * HashMap.set(mutable, "b", 2)
703 * HashMap.set(mutable, "c", 3)
704 * HashMap.remove(mutable, "a")
705 *
706 * // End mutation to get final immutable result
707 * const result = HashMap.endMutation(mutable)
708 * console.log(HashMap.size(result)) // 2
709 * ```
710 *
711 * @category mutations
712 * @since 2.0.0
713 */
714export const beginMutation: <K, V>(self: HashMap<K, V>) => HashMap<K, V> = internal.beginMutation
715​
716/**
717 * Marks the `HashMap` as immutable, completing the mutation cycle.
718 *
719 * **Example** (Ending batch mutation)
720 *
721 * ```ts
722 * import { HashMap } from "effect"
723 *
724 * // Start with an existing map
725 * const original = HashMap.make(["x", 10], ["y", 20])
726 *
727 * // Begin mutation for batch operations
728 * const mutable = HashMap.beginMutation(original)
729 *
730 * // Perform multiple efficient operations
731 * HashMap.set(mutable, "z", 30)
732 * HashMap.remove(mutable, "x")
733 * HashMap.set(mutable, "w", 40)
734 *
735 * // End mutation to get final immutable result
736 * const final = HashMap.endMutation(mutable)
737 *
738 * console.log(HashMap.size(final)) // 3
739 * console.log(HashMap.has(final, "x")) // false
740 * console.log(HashMap.get(final, "z")) // Option.some(30)
741 * ```
742 *
743 * @category mutations
744 * @since 2.0.0
745 */
746export const endMutation: <K, V>(self: HashMap<K, V>) => HashMap<K, V> = internal.endMutation
747​
748/**
749 * Runs a batch of updates against a transient mutable copy of the `HashMap`
750 * and returns the finalized immutable result.
751 *
752 * **Details**
753 *
754 * The callback may call mutation-oriented helpers such as `set` and `remove`
755 * on the transient map.
756 *
757 * **Example** (Applying batched mutations)
758 *
759 * ```ts
760 * import { HashMap } from "effect"
761 *
762 * const map1 = HashMap.make(["a", 1])
763 * const map2 = HashMap.mutate(map1, (mutable) => {
764 * HashMap.set(mutable, "b", 2)
765 * HashMap.set(mutable, "c", 3)
766 * })
767 * // Returns a new HashMap with mutations applied
768 * ```
769 *
770 * @category mutations
771 * @since 2.0.0
772 */
773export const mutate: {
774 <K, V>(f: (self: HashMap<K, V>) => void): (self: HashMap<K, V>) => HashMap<K, V>
775 <K, V>(self: HashMap<K, V>, f: (self: HashMap<K, V>) => void): HashMap<K, V>
776} = internal.mutate
777​
778/**
779 * Sets or removes the specified key using an update function.
780 *
781 * **Details**
782 *
783 * The update function receives `Some(value)` when the key exists or `None`
784 * when it does not. Returning `Some(newValue)` stores the value, and returning
785 * `None` removes the key or leaves it absent.
786 *
787 * **Example** (Updating values with Options)
788 *
789 * ```ts
790 * import { HashMap, Option } from "effect"
791 *
792 * const map = HashMap.make(["a", 1], ["b", 2])
793 *
794 * // Increment existing value or set to 1 if not present
795 * const updateFn = (option: Option.Option<number>) =>
796 * Option.isSome(option) ? Option.some(option.value + 1) : Option.some(1)
797 *
798 * const updated = HashMap.modifyAt(map, "a", updateFn)
799 * console.log(HashMap.get(updated, "a")) // Option.some(2)
800 * ```
801 *
802 * @category transforming
803 * @since 2.0.0
804 */
805export const modifyAt: {
806 <K, V>(key: K, f: HashMap.UpdateFn<V>): (self: HashMap<K, V>) => HashMap<K, V>
807 <K, V>(self: HashMap<K, V>, key: K, f: HashMap.UpdateFn<V>): HashMap<K, V>
808} = internal.modifyAt
809​
810/**
811 * Sets or removes the specified key using a precomputed hash and an update
812 * function.
813 *
814 * **Details**
815 *
816 * The update function receives `Some(value)` when the key exists or `None`
817 * when it does not. Returning `Some(newValue)` stores the value, and returning
818 * `None` removes the key or leaves it absent.
819 *
820 * **Example** (Updating values with a hash)
821 *
822 * ```ts
823 * import { Hash, HashMap, Option } from "effect"
824 *
825 * // Useful when working with precomputed hashes for performance
826 * const counters = HashMap.make(["downloads", 100], ["views", 250])
827 *
828 * // Cache hash computation for frequently accessed keys
829 * const metricKey = "downloads"
830 * const cachedHash = Hash.string(metricKey)
831 *
832 * // Update function that increments counter or initializes to 1
833 * const incrementCounter = (current: Option.Option<number>) =>
834 * Option.isSome(current) ? Option.some(current.value + 1) : Option.some(1)
835 *
836 * // Use cached hash for efficient updates in loops
837 * const updated = HashMap.modifyHash(
838 * counters,
839 * metricKey,
840 * cachedHash,
841 * incrementCounter
842 * )
843 * console.log(HashMap.get(updated, "downloads")) // Option.some(101)
844 *
845 * // Add new metric with precomputed hash
846 * const newMetric = "clicks"
847 * const clicksHash = Hash.string(newMetric)
848 * const withClicks = HashMap.modifyHash(
849 * updated,
850 * newMetric,
851 * clicksHash,
852 * incrementCounter
853 * )
854 * console.log(HashMap.get(withClicks, "clicks")) // Option.some(1)
855 * ```
856 *
857 * @category transforming
858 * @since 2.0.0
859 */
860export const modifyHash: {
861 <K, V>(key: K, hash: number, f: HashMap.UpdateFn<V>): (self: HashMap<K, V>) => HashMap<K, V>
862 <K, V>(self: HashMap<K, V>, key: K, hash: number, f: HashMap.UpdateFn<V>): HashMap<K, V>
863} = internal.modifyHash
864​
865/**
866 * Updates the value of the specified key within the `HashMap` if it exists.
867 *
868 * **Example** (Modifying existing values)
869 *
870 * ```ts
871 * import { HashMap } from "effect"
872 *
873 * const map1 = HashMap.make(["a", 1], ["b", 2])
874 * const map2 = HashMap.modify(map1, "a", (value) => value * 3)
875 *
876 * console.log(HashMap.get(map2, "a")) // Option.some(3)
877 * console.log(HashMap.get(map2, "b")) // Option.some(2)
878 * ```
879 *
880 * @category transforming
881 * @since 2.0.0
882 */
883export const modify: {
884 <K, V>(key: K, f: (v: V) => V): (self: HashMap<K, V>) => HashMap<K, V>
885 <K, V>(self: HashMap<K, V>, key: K, f: (v: V) => V): HashMap<K, V>
886} = internal.modify
887​
888/**
889 * Combines two `HashMap`s into one.
890 *
891 * **Details**
892 *
893 * Entries from `that` are inserted into `self`; when both maps contain an
894 * equal key, the value from `that` replaces the value from `self`.
895 *
896 * **Example** (Combining HashMaps)
897 *
898 * ```ts
899 * import { HashMap } from "effect"
900 *
901 * const map1 = HashMap.make(["a", 1], ["b", 2])
902 * const map2 = HashMap.make(["b", 20], ["c", 3])
903 * const union = HashMap.union(map1, map2)
904 *
905 * console.log(HashMap.size(union)) // 3
906 * console.log(HashMap.get(union, "b")) // Option.some(20) - map2 wins
907 * ```
908 *
909 * @category combining
910 * @since 2.0.0
911 */
912export const union: {
913 <K1, V1>(that: HashMap<K1, V1>): <K0, V0>(self: HashMap<K0, V0>) => HashMap<K1 | K0, V1 | V0>
914 <K0, V0, K1, V1>(self: HashMap<K0, V0>, that: HashMap<K1, V1>): HashMap<K0 | K1, V0 | V1>
915} = internal.union
916​
917/**
918 * Removes the entry for the specified key in the `HashMap` using the internal
919 * hashing function.
920 *
921 * **Example** (Removing a key)
922 *
923 * ```ts
924 * import { HashMap } from "effect"
925 *
926 * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3])
927 * const map2 = HashMap.remove(map1, "b")
928 *
929 * console.log(HashMap.size(map2)) // 2
930 * console.log(HashMap.has(map2, "b")) // false
931 * console.log(HashMap.has(map2, "a")) // true
932 * ```
933 *
934 * @category transforming
935 * @since 2.0.0
936 */
937export const remove: {
938 <K>(key: K): <V>(self: HashMap<K, V>) => HashMap<K, V>
939 <K, V>(self: HashMap<K, V>, key: K): HashMap<K, V>
940} = internal.remove
941​
942/**
943 * Removes all entries in the `HashMap` which have the specified keys.
944 *
945 * **Example** (Removing multiple keys)
946 *
947 * ```ts
948 * import { HashMap } from "effect"
949 *
950 * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4])
951 * const map2 = HashMap.removeMany(map1, ["b", "d"])
952 *
953 * console.log(HashMap.size(map2)) // 2
954 * console.log(HashMap.has(map2, "a")) // true
955 * console.log(HashMap.has(map2, "c")) // true
956 * ```
957 *
958 * @category transforming
959 * @since 2.0.0
960 */
961export const removeMany: {
962 <K>(keys: Iterable<K>): <V>(self: HashMap<K, V>) => HashMap<K, V>
963 <K, V>(self: HashMap<K, V>, keys: Iterable<K>): HashMap<K, V>
964} = internal.removeMany
965​
966/**
967 * Sets multiple key-value pairs in the `HashMap`.
968 *
969 * **Example** (Setting multiple entries)
970 *
971 * ```ts
972 * import { HashMap } from "effect"
973 *
974 * const map1 = HashMap.make(["a", 1], ["b", 2])
975 * const newEntries = [["c", 3], ["d", 4], ["a", 10]] as const // "a" will be overwritten
976 * const map2 = HashMap.setMany(map1, newEntries)
977 *
978 * console.log(HashMap.size(map2)) // 4
979 * console.log(HashMap.get(map2, "a")) // Option.some(10)
980 * console.log(HashMap.get(map2, "c")) // Option.some(3)
981 * ```
982 *
983 * @category transforming
984 * @since 4.0.0
985 */
986export const setMany: {
987 <K, V>(entries: Iterable<readonly [K, V]>): (self: HashMap<K, V>) => HashMap<K, V>
988 <K, V>(self: HashMap<K, V>, entries: Iterable<readonly [K, V]>): HashMap<K, V>
989} = internal.setMany
990​
991/**
992 * Maps over the entries of the `HashMap` using the specified function.
993 *
994 * **Example** (Mapping values)
995 *
996 * ```ts
997 * import { HashMap } from "effect"
998 *
999 * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3])
1000 * const map2 = HashMap.map(map1, (value, key) => `${key}:${value * 2}`)
1002 * console.log(HashMap.get(map2, "a")) // Option.some("a:2")
1003 * console.log(HashMap.get(map2, "b")) // Option.some("b:4")
1004 * ```
1006 * @category mapping
1007 * @since 2.0.0
1008 */
1009export const map: {
1010 <A, V, K>(f: (value: V, key: K) => A): (self: HashMap<K, V>) => HashMap<K, A>
1011 <K, V, A>(self: HashMap<K, V>, f: (value: V, key: K) => A): HashMap<K, A>
1012} = internal.map
1013​
1014/**
1015 * Maps each entry to a `HashMap` and flattens the results.
1017 * **Gotchas**
1019 * The hash and equality behavior of both maps have to be the same.
1021 * **Example** (Flat mapping values)
1023 * ```ts
1024 * import { HashMap } from "effect"
1026 * const map1 = HashMap.make(["a", 1], ["b", 2])
1027 * const map2 = HashMap.flatMap(
1028 * map1,
1029 * (value, key) => HashMap.make([key + "1", value], [key + "2", value * 2])
1030 * )
1032 * console.log(HashMap.size(map2)) // 4
1033 * console.log(HashMap.get(map2, "a1")) // Option.some(1)
1034 * console.log(HashMap.get(map2, "b2")) // Option.some(4)
1035 * ```
1037 * @category sequencing
1038 * @since 2.0.0
1039 */
1040export const flatMap: {
1041 <A, K, B>(f: (value: A, key: K) => HashMap<K, B>): (self: HashMap<K, A>) => HashMap<K, B>
1042 <K, A, B>(self: HashMap<K, A>, f: (value: A, key: K) => HashMap<K, B>): HashMap<K, B>
1043} = internal.flatMap
1044​
1045/**
1046 * Applies the specified function to the entries of the `HashMap`.
1048 * **Example** (Iterating with side effects)
1050 * ```ts
1051 * import { HashMap } from "effect"
1053 * const map = HashMap.make(["a", 1], ["b", 2])
1054 * const collected: Array<[string, number]> = []
1056 * HashMap.forEach(map, (value, key) => {
1057 * collected.push([key, value])
1058 * })
1060 * console.log(collected.sort()) // [["a", 1], ["b", 2]]
1061 * ```
1063 * @category traversing
1064 * @since 2.0.0
1065 */
1066export const forEach: {
1067 <V, K>(f: (value: V, key: K) => void): (self: HashMap<K, V>) => void
1068 <V, K>(self: HashMap<K, V>, f: (value: V, key: K) => void): void
1069} = internal.forEach
1070​
1071/**
1072 * Reduces the specified state over the entries of the `HashMap`.
1074 * **Example** (Reducing values)
1076 * ```ts
1077 * import { HashMap } from "effect"
1079 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
1080 * const sum = HashMap.reduce(map, 0, (acc, value) => acc + value)
1082 * console.log(sum) // 6
1083 * ```
1085 * @category folding
1086 * @since 2.0.0
1087 */
1088export const reduce: {
1089 <Z, V, K>(zero: Z, f: (accumulator: Z, value: V, key: K) => Z): (self: HashMap<K, V>) => Z
1090 <K, V, Z>(self: HashMap<K, V>, zero: Z, f: (accumulator: Z, value: V, key: K) => Z): Z
1091} = internal.reduce
1092​
1093/**
1094 * Filters entries out of a `HashMap` using the specified predicate.
1096 * **Example** (Filtering entries)
1098 * ```ts
1099 * import { HashMap } from "effect"
1101 * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4])
1102 * const map2 = HashMap.filter(map1, (value) => value % 2 === 0)
1104 * console.log(HashMap.size(map2)) // 2
1105 * console.log(HashMap.has(map2, "b")) // true
1106 * console.log(HashMap.has(map2, "d")) // true
1107 * console.log(HashMap.has(map2, "a")) // false
1108 * ```
1110 * @category filtering
1111 * @since 2.0.0
1112 */
1113export const filter: {
1114 <K, A>(f: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => HashMap<K, A>
1115 <K, A>(self: HashMap<K, A>, f: (a: A, k: K) => boolean): HashMap<K, A>
1116} = internal.filter
1117​
1118/**
1119 * Filters out `None` values from a `HashMap` of `Options`s.
1121 * **Example** (Compacting Option values)
1123 * ```ts
1124 * import { HashMap, Option } from "effect"
1126 * const map1 = HashMap.make(
1127 * ["a", Option.some(1)],
1128 * ["b", Option.none()],
1129 * ["c", Option.some(3)]
1130 * )
1131 * const map2 = HashMap.compact(map1)
1133 * console.log(HashMap.size(map2)) // 2
1134 * console.log(HashMap.get(map2, "a")) // Option.some(1)
1135 * console.log(HashMap.has(map2, "b")) // false
1136 * ```
1138 * @category filtering
1139 * @since 2.0.0
1140 */
1141export const compact: <K, A>(self: HashMap<K, Option<A>>) => HashMap<K, A> = internal.compact
1142​
1143/**
1144 * Maps over the entries of the `HashMap` using the specified filter and keeps
1145 * only successful results.
1147 * **Example** (Filtering and mapping Results)
1149 * ```ts
1150 * import { HashMap, Result } from "effect"
1152 * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4])
1153 * const map2 = HashMap.filterMap(
1154 * map1,
1155 * (value) => value % 2 === 0 ? Result.succeed(value * 2) : Result.failVoid
1156 * )
1158 * console.log(HashMap.size(map2)) // 2
1159 * console.log(HashMap.get(map2, "b")) // Option.some(4)
1160 * console.log(HashMap.get(map2, "d")) // Option.some(8)
1161 * ```
1163 * @category filtering
1164 * @since 2.0.0
1165 */
1166export const filterMap: {
1167 <A, K, B, X>(f: (input: A, key: K) => Result<B, X>): (self: HashMap<K, A>) => HashMap<K, B>
1168 <K, A, B, X>(self: HashMap<K, A>, f: (input: A, key: K) => Result<B, X>): HashMap<K, B>
1169} = internal.filterMap
1170​
1171/**
1172 * Returns the first element that satisfies the specified
1173 * predicate, or `None` if no such element exists.
1175 * **Example** (Finding the first matching entry)
1177 * ```ts
1178 * import { HashMap, Option } from "effect"
1180 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
1181 * const result = HashMap.findFirst(map, (value, key) => key === "b" && value > 1)
1182 * console.log(result) // Option.some(["b", 2])
1183 * console.log(Option.getOrElse(result, () => ["", 0])) // ["b", 2]
1184 * ```
1186 * @category elements
1187 * @since 2.0.0
1188 */
1189export const findFirst: {
1190 <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => Option<[K, A]>
1191 <K, A>(self: HashMap<K, A>, predicate: (a: A, k: K) => boolean): Option<[K, A]>
1192} = internal.findFirst
1193​
1194/**
1195 * Checks whether any entry in a hashmap meets a specific condition.
1197 * **Example** (Checking for any matching entry)
1199 * ```ts
1200 * import { HashMap } from "effect"
1202 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
1204 * console.log(HashMap.some(map, (value) => value > 2)) // true
1205 * console.log(HashMap.some(map, (value) => value > 5)) // false
1206 * ```
1208 * @category elements
1209 * @since 3.13.0
1210 */
1211export const some: {
1212 <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => boolean
1213 <K, A>(self: HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean
1214} = internal.some
1215​
1216/**
1217 * Checks whether all entries in a hashmap meets a specific condition.
1219 * **Example** (Checking all entries)
1221 * ```ts
1222 * import { HashMap } from "effect"
1224 * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3])
1226 * console.log(HashMap.every(map, (value) => value > 0)) // true
1227 * console.log(HashMap.every(map, (value) => value > 1)) // false
1228 * ```
1230 * @category elements
1231 * @since 3.14.0
1232 */
1233export const every: {
1234 <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => boolean
1235 <K, A>(self: HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean
1236} = internal.every