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