Open History to see the last commit
1/**
2 * `MutableHashSet` is an in-place hash set for storing unique values with fast
3 * membership checks, insertion, removal, clearing, and iteration. It is built on
4 * {@link MutableHashMap}: each set value is stored as a map key, so uniqueness
5 * follows the same hashing and equality rules as the underlying mutable hash
6 * map.
7 *
8 * **Mental model**
9 *
10 * - `MutableHashSet<V>` is a mutable collection of unique values of type `V`
11 * - {@link add}, {@link remove}, and {@link clear} mutate the same set instance
12 * - Duplicate values are ignored according to Effect equality and hashing
13 * semantics
14 * - Values that implement `Equal` / `Hash` can be compared structurally;
15 * primitive values and ordinary object references use the underlying hash map
16 * behavior
17 * - The set is iterable, so `for...of` and `Array.from(set)` can inspect the
18 * current values
19 *
20 * **Common tasks**
21 *
22 * - Create an empty set: {@link empty}
23 * - Create from values or an iterable: {@link make}, {@link fromIterable}
24 * - Add, remove, and clear values: {@link add}, {@link remove}, {@link clear}
25 * - Check membership and size: {@link has}, {@link size}
26 * - Narrow unknown values: {@link isMutableHashSet}
27 *
28 * **Gotchas**
29 *
30 * - This data structure is intentionally mutable; keep ownership clear if the
31 * same set is shared by multiple callers
32 * - Mutating operations return the same set instance for convenient piping
33 * - Do not use iteration order as a sorting or presentation guarantee
34 * - Use immutable collection modules when callers need persistent snapshots
35 *
36 * **Performance**
37 *
38 * - Add, membership checks, and removal are O(1) on average
39 * - Hash collisions can make those operations O(n)
40 * - Clearing and reading size are O(1)
41 * - Iteration is O(n)
42 *
43 * **Quickstart**
44 *
45 * **Example** (Tracking unique values)
46 *
47 * ```ts
48 * import { MutableHashSet } from "effect"
49 *
50 * const set = MutableHashSet.make("alice", "bob", "alice")
51 *
52 * MutableHashSet.add(set, "carol")
53 * MutableHashSet.remove(set, "bob")
54 *
55 * console.log(MutableHashSet.has(set, "alice"))
56 * // Output: true
57 *
58 * console.log(MutableHashSet.size(set))
59 * // Output: 2
60 * ```
61 *
62 * **See also**
63 *
64 * - {@link MutableHashMap} for the mutable key-value structure underneath
65 * - {@link empty}, {@link make}, and {@link fromIterable} for construction
66 * - {@link add}, {@link remove}, and {@link has} for core set operations
67 *
68 * @since 2.0.0
69 */
70import { format } from "./Formatter.ts"
71import * as Dual from "./Function.ts"
72import { type Inspectable, NodeInspectSymbol, toJson } from "./Inspectable.ts"
73import * as MutableHashMap from "./MutableHashMap.ts"
74import type { Pipeable } from "./Pipeable.ts"
75import { pipeArguments } from "./Pipeable.ts"
76import { hasProperty } from "./Predicate.ts"
77
78const TypeId = "~effect/collections/MutableHashSet"
79
80/**
81 * A mutable hash set for storing unique values with Effect structural equality
82 * support.
83 *
84 * **When to use**
85 *
86 * Use to store and mutate a collection of unique values with Effect hashing and
87 * equality semantics.
88 *
89 * **Details**
90 *
91 * Operations mutate the set in place. Values that implement `Equal` / `Hash`
92 * can be de-duplicated structurally; other values use normal JavaScript
93 * reference or primitive equality.
94 *
95 * **Example** (Using a mutable hash set)
96 *
97 * ```ts
98 * import { MutableHashSet } from "effect"
99 *
100 * // Create a mutable hash set
101 * const set: MutableHashSet.MutableHashSet<string> = MutableHashSet.make(
102 * "apple",
103 * "banana"
104 * )
105 *
106 * // Add elements
107 * MutableHashSet.add(set, "cherry")
108 *
109 * // Check if elements exist
110 * console.log(MutableHashSet.has(set, "apple")) // true
111 * console.log(MutableHashSet.has(set, "grape")) // false
112 *
113 * // Iterate over elements
114 * for (const value of set) {
115 * console.log(value) // "apple", "banana", "cherry"
116 * }
117 *
118 * // Get size
119 * console.log(MutableHashSet.size(set)) // 3
120 * ```
121 *
122 * @category models
123 * @since 2.0.0
124 */
125export interface MutableHashSet<out V> extends Iterable<V>, Pipeable, Inspectable {
126 readonly [TypeId]: typeof TypeId
127 readonly keyMap: MutableHashMap.MutableHashMap<V, boolean>
128}
129
130/**
131 * Checks whether the specified value is a `MutableHashSet`, `false` otherwise.
132 *
133 * **When to use**
134 *
135 * Use to narrow an unknown value before treating it as a mutable hash set.
136 *
137 * **Details**
138 *
139 * The check looks for the `MutableHashSet` runtime marker.
140 *
141 * **Gotchas**
142 *
143 * Native `Set` values do not satisfy this check.
144 *
145 * @see {@link MutableHashSet} for the mutable hash set interface
146 *
147 * @category refinements
148 * @since 4.0.0
149 */
150export const isMutableHashSet = <V>(value: unknown): value is MutableHashSet<V> => hasProperty(value, TypeId)
151
152const MutableHashSetProto: Omit<MutableHashSet<unknown>, "keyMap"> = {
153 [TypeId]: TypeId,
154 [Symbol.iterator](this: MutableHashSet<unknown>): Iterator<unknown> {
155 return Array.from(this.keyMap).map(([_]) => _)[Symbol.iterator]()
156 },
157 toString() {
158 return `MutableHashSet(${format(Array.from(this))})`
159 },
160 toJSON() {
161 return {
162 _id: "MutableHashSet",
163 values: toJson(Array.from(this))
164 }
165 },
166 [NodeInspectSymbol]() {
167 return this.toJSON()
168 },
169 pipe() {
170 return pipeArguments(this, arguments)
171 }
172}
173
174const fromHashMap = <V>(keyMap: MutableHashMap.MutableHashMap<V, boolean>): MutableHashSet<V> => {
175 const set = Object.create(MutableHashSetProto)
176 set.keyMap = keyMap
177 return set
178}
179
180/**
181 * Creates an empty MutableHashSet.
182 *
183 * **When to use**
184 *
185 * Use to create a fresh mutable set before adding values over time.
186 *
187 * **Details**
188 *
189 * Each call returns a new empty set backed by an empty `MutableHashMap`.
190 *
191 * **Example** (Creating an empty set)
192 *
193 * ```ts
194 * import { MutableHashSet } from "effect"
195 *
196 * const set = MutableHashSet.empty<string>()
197 *
198 * // Add some values
199 * MutableHashSet.add(set, "apple")
200 * MutableHashSet.add(set, "banana")
201 * MutableHashSet.add(set, "apple") // Duplicate, no effect
202 *
203 * console.log(MutableHashSet.size(set)) // 2
204 * console.log(Array.from(set)) // ["apple", "banana"]
205 * ```
206 *
207 * @see {@link make} for creating a set from explicit values
208 * @see {@link fromIterable} for creating a set from an iterable of values
209 * @see {@link clear} for emptying an existing mutable set
210 *
211 * @category constructors
212 * @since 2.0.0
213 */
214export const empty = <K = never>(): MutableHashSet<K> => fromHashMap(MutableHashMap.empty())
215
216/**
217 * Creates a MutableHashSet from an iterable collection of values.
218 * Duplicates are automatically removed.
219 *
220 * **When to use**
221 *
222 * Use to build a mutable hash set from any iterable of values.
223 *
224 * **Example** (Creating a set from an iterable)
225 *
226 * ```ts
227 * import { MutableHashSet } from "effect"
228 *
229 * const values = ["apple", "banana", "apple", "cherry", "banana"]
230 * const set = MutableHashSet.fromIterable(values)
231 *
232 * console.log(MutableHashSet.size(set)) // 3
233 * console.log(Array.from(set)) // ["apple", "banana", "cherry"]
234 *
235 * // Works with any iterable
236 * const fromSet = MutableHashSet.fromIterable(new Set([1, 2, 3]))
237 * console.log(MutableHashSet.size(fromSet)) // 3
238 *
239 * // From string characters
240 * const fromString = MutableHashSet.fromIterable("hello")
241 * console.log(Array.from(fromString)) // ["h", "e", "l", "o"]
242 * ```
243 *
244 * @category constructors
245 * @since 2.0.0
246 */
247export const fromIterable = <K = never>(keys: Iterable<K>): MutableHashSet<K> =>
248 fromHashMap(MutableHashMap.fromIterable(Array.from(keys).map((k) => [k, true])))
249
250/**
251 * Creates a MutableHashSet from a variable number of values.
252 * Duplicates are automatically removed.
253 *
254 * **When to use**
255 *
256 * Use to build a mutable hash set from explicit values.
257 *
258 * **Example** (Creating a set from values)
259 *
260 * ```ts
261 * import { MutableHashSet } from "effect"
262 *
263 * const set = MutableHashSet.make("apple", "banana", "apple", "cherry")
264 *
265 * console.log(MutableHashSet.size(set)) // 3
266 * console.log(Array.from(set)) // ["apple", "banana", "cherry"]
267 *
268 * // With numbers
269 * const numbers = MutableHashSet.make(1, 2, 3, 2, 1)
270 * console.log(MutableHashSet.size(numbers)) // 3
271 * console.log(Array.from(numbers)) // [1, 2, 3]
272 *
273 * // Mixed types
274 * const mixed = MutableHashSet.make("hello", 42, true, "hello")
275 * console.log(MutableHashSet.size(mixed)) // 3
276 * ```
277 *
278 * @category constructors
279 * @since 2.0.0
280 */
281export const make = <Keys extends ReadonlyArray<unknown>>(
282 ...keys: Keys
283): MutableHashSet<Keys[number]> => fromIterable(keys)
284
285/**
286 * Adds a value to the MutableHashSet, mutating the set in place.
287 * If the value already exists, the set remains unchanged.
288 *
289 * **When to use**
290 *
291 * Use to insert a value into a mutable set while keeping uniqueness.
292 *
293 * **Example** (Adding values)
294 *
295 * ```ts
296 * import { MutableHashSet } from "effect"
297 *
298 * const set = MutableHashSet.empty<string>()
299 *
300 * // Add new values
301 * MutableHashSet.add(set, "apple")
302 * MutableHashSet.add(set, "banana")
303 *
304 * console.log(MutableHashSet.size(set)) // 2
305 * console.log(MutableHashSet.has(set, "apple")) // true
306 *
307 * // Add duplicate (no effect)
308 * MutableHashSet.add(set, "apple")
309 * console.log(MutableHashSet.size(set)) // 2
310 *
311 * // Pipe-able version
312 * const addFruit = MutableHashSet.add("cherry")
313 * addFruit(set)
314 * console.log(MutableHashSet.size(set)) // 3
315 * ```
316 *
317 * @category mutations
318 * @since 2.0.0
319 */
320export const add: {
321 <V>(key: V): (self: MutableHashSet<V>) => MutableHashSet<V>
322 <V>(self: MutableHashSet<V>, key: V): MutableHashSet<V>
323} = Dual.dual<
324 <V>(key: V) => (self: MutableHashSet<V>) => MutableHashSet<V>,
325 <V>(self: MutableHashSet<V>, key: V) => MutableHashSet<V>
326>(2, (self, key) => (MutableHashMap.set(self.keyMap, key, true), self))
327
328/**
329 * Checks whether the MutableHashSet contains the specified value.
330 *
331 * **When to use**
332 *
333 * Use to test whether a mutable set currently contains a value.
334 *
335 * **Details**
336 *
337 * Membership follows the same hashing and equality rules as the underlying
338 * `MutableHashMap`.
339 *
340 * **Example** (Checking for a value)
341 *
342 * ```ts
343 * import { MutableHashSet } from "effect"
344 *
345 * const set = MutableHashSet.make("apple", "banana", "cherry")
346 *
347 * console.log(MutableHashSet.has(set, "apple")) // true
348 * console.log(MutableHashSet.has(set, "grape")) // false
349 *
350 * // Pipe-able version
351 * const hasApple = MutableHashSet.has("apple")
352 * console.log(hasApple(set)) // true
353 *
354 * // Check after adding
355 * MutableHashSet.add(set, "grape")
356 * console.log(MutableHashSet.has(set, "grape")) // true
357 * ```
358 *
359 * @see {@link add} for adding a value to the set
360 * @see {@link remove} for removing a value from the set
361 *
362 * @category elements
363 * @since 2.0.0
364 */
365export const has: {
366 <V>(key: V): (self: MutableHashSet<V>) => boolean
367 <V>(self: MutableHashSet<V>, key: V): boolean
368} = Dual.dual<
369 <V>(key: V) => (self: MutableHashSet<V>) => boolean,
370 <V>(self: MutableHashSet<V>, key: V) => boolean
371>(2, (self, key) => MutableHashMap.has(self.keyMap, key))
372
373/**
374 * Removes the specified value from the MutableHashSet, mutating the set in place.
375 * If the value doesn't exist, the set remains unchanged.
376 *
377 * **When to use**
378 *
379 * Use to delete a value from a mutable set if it is present.
380 *
381 * **Example** (Removing a value)
382 *
383 * ```ts
384 * import { MutableHashSet } from "effect"
385 *
386 * const set = MutableHashSet.make("apple", "banana", "cherry")
387 *
388 * console.log(MutableHashSet.size(set)) // 3
389 *
390 * // Remove existing value
391 * MutableHashSet.remove(set, "banana")
392 * console.log(MutableHashSet.size(set)) // 2
393 * console.log(MutableHashSet.has(set, "banana")) // false
394 *
395 * // Remove non-existent value (no effect)
396 * MutableHashSet.remove(set, "grape")
397 * console.log(MutableHashSet.size(set)) // 2
398 *
399 * // Pipe-able version
400 * const removeFruit = MutableHashSet.remove("apple")
401 * removeFruit(set)
402 * console.log(MutableHashSet.size(set)) // 1
403 * ```
404 *
405 * @category mutations
406 * @since 2.0.0
407 */
408export const remove: {
409 <V>(key: V): (self: MutableHashSet<V>) => MutableHashSet<V>
410 <V>(self: MutableHashSet<V>, key: V): MutableHashSet<V>
411} = Dual.dual<
412 <V>(key: V) => (self: MutableHashSet<V>) => MutableHashSet<V>,
413 <V>(self: MutableHashSet<V>, key: V) => MutableHashSet<V>
414>(2, (self, key) => (MutableHashMap.remove(self.keyMap, key), self))
415
416/**
417 * Returns the number of unique values in the MutableHashSet.
418 *
419 * **When to use**
420 *
421 * Use to read how many unique values are currently stored in the set.
422 *
423 * **Example** (Checking set size)
424 *
425 * ```ts
426 * import { MutableHashSet } from "effect"
427 *
428 * const set = MutableHashSet.empty<string>()
429 * console.log(MutableHashSet.size(set)) // 0
430 *
431 * MutableHashSet.add(set, "apple")
432 * MutableHashSet.add(set, "banana")
433 * MutableHashSet.add(set, "apple") // Duplicate
434 * console.log(MutableHashSet.size(set)) // 2
435 *
436 * MutableHashSet.remove(set, "apple")
437 * console.log(MutableHashSet.size(set)) // 1
438 *
439 * MutableHashSet.clear(set)
440 * console.log(MutableHashSet.size(set)) // 0
441 * ```
442 *
443 * @category elements
444 * @since 2.0.0
445 */
446export const size = <V>(self: MutableHashSet<V>): number => MutableHashMap.size(self.keyMap)
447
448/**
449 * Removes all values from the MutableHashSet, mutating the set in place.
450 * The set becomes empty after this operation.
451 *
452 * **When to use**
453 *
454 * Use to empty a mutable set while keeping the same set instance.
455 *
456 * **Example** (Clearing all values)
457 *
458 * ```ts
459 * import { MutableHashSet } from "effect"
460 *
461 * const set = MutableHashSet.make("apple", "banana", "cherry")
462 *
463 * console.log(MutableHashSet.size(set)) // 3
464 *
465 * // Clear all values
466 * MutableHashSet.clear(set)
467 *
468 * console.log(MutableHashSet.size(set)) // 0
469 * console.log(MutableHashSet.has(set, "apple")) // false
470 * console.log(Array.from(set)) // []
471 *
472 * // Can still add new values after clearing
473 * MutableHashSet.add(set, "new")
474 * console.log(MutableHashSet.size(set)) // 1
475 * ```
476 *
477 * @category mutations
478 * @since 2.0.0
479 */
480export const clear = <V>(self: MutableHashSet<V>): MutableHashSet<V> => (MutableHashMap.clear(self.keyMap), self)