Skip to content

HashSet

HashSet and MutableHashSet store unique, unordered values deduplicated by Effect's structural Equal and Hash protocols rather than JavaScript reference identity. Use HashSet for immutable snapshots shared across fibers, and MutableHashSet for single-owner local accumulation.

CollectionMutabilityEqualityBest for
HashSetPersistent (structural sharing)Equal + HashShared state, version history, set algebra
MutableHashSetIn-place mutationEqual + HashLocal builders before freezing into a HashSet
Native SetIn-place mutationJavaScript SameValueZeroInsertion-ordered primitives or reference identity

Choosing immutable or mutable sets

const snapshot = HashSet.make("green", "blue")
const revised = HashSet.add(snapshot, "red")
HashSet.has(snapshot, "red") // false
HashSet.has(revised, "red") // true
 
function buildLocal() {
  const working = MutableHashSet.empty<string>()
  MutableHashSet.add(working, "green")
  MutableHashSet.add(working, "blue")
  return HashSet.fromIterable(working)
}
// Run in an effect function:
//   try Console.log(HashSet.has(snapshot, "red"), HashSet.has(revised, "red"))
//   try Console.log(try Effect.try(() => JSON.stringify(Array.from(buildLocal()).sort())))
false true
["blue","green"]

Immutable updates preserve earlier snapshots without defensive copies, making them safe to share across fibers. Use an array when insertion order or indexing matters, and HashMap for key-value associations.

Equality and uniqueness

const a = { region: "west", active: true }
const b = { region: "west", active: true }
Equal.equals(a, b) // true
HashSet.size(HashSet.make(a, b)) // 1
new Set([a, b]).size // 2
// Run in an effect function: try Console.log(Equal.equals(a, b), HashSet.size(HashSet.make(a, b)), new Set([a, b]).size)
true 1 2

In Effect 4.1.1, plain objects compare structurally, so separately allocated records with identical fields collapse to one member—every field counts. For custom identity, implement Equal.Equal with a matching Hash.Hash, and never mutate members after insertion.

Constructing and changing immutable sets

const empty = HashSet.empty<number>()
const initial = HashSet.fromIterable([2, 4, 4, 6])
const changed = HashSet.remove(HashSet.add(initial, 8), 2)
const other = HashSet.make(6, 10)
const together = HashSet.union(changed, other)
const common = HashSet.intersection(changed, other)
const exclusive = HashSet.difference(changed, other)
const large = HashSet.filter(together, (n) => n > 5)
const labels = HashSet.map(large, (n) => `item-${n}`)
const sum = HashSet.reduce(initial, 0, (total, n) => total + n)
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([Array.from(initial).sort(Order.Number), Array.from(changed).sort(Order.Number), Array.from(together).sort(Order.Number), Array.from(common).sort(Order.Number), Array.from(exclusive).sort(Order.Number), Array.from(large).sort(Order.Number), Array.from(labels).sort(), sum, HashSet.size(empty)])))
[[2,4,6],[4,6,8],[4,6,8,10],[6],[4,8],[6,8,10],["item-10","item-6","item-8"],12,0]

Construct sets with empty, make, or fromIterable. add, remove, union, intersection, difference, filter, and map all return new sets without altering inputs.

Querying membership and size

const allowed = HashSet.make("read", "write", "audit")
HashSet.has(allowed, "write") // true
HashSet.size(allowed) // 3
HashSet.some(allowed, (name) => name.startsWith("a")) // true
HashSet.every(allowed, (name) => name.length > 0) // true
HashSet.isSubset(HashSet.make("read"), allowed) // true
// Run in an effect function: try Console.log(HashSet.has(allowed, "write"), HashSet.size(allowed), HashSet.some(allowed, (name) => name.startsWith("a")), HashSet.every(allowed, (name) => name.length > 0), HashSet.isSubset(HashSet.make("read"), allowed))
true 3 true true true

has checks membership, size returns the unique count, some and every test predicates over members, and isSubset checks containment. Iteration order is unspecified.

Updating mutable sets

function uniqueRegions(regions: ReadonlyArray<string>) {
  const seen = MutableHashSet.fromIterable(regions)
  MutableHashSet.add(seen, "unknown")
  MutableHashSet.remove(seen, "")
  const count = MutableHashSet.size(seen)
  const containsUnknown = MutableHashSet.has(seen, "unknown")
  const values = Array.from(seen)
  MutableHashSet.clear(seen)
  return { count, containsUnknown, values }
}
// Run in an effect function:
//   const result = uniqueRegions(["west", "west", ""])
//   try Console.log(result.count, result.containsUnknown, try Effect.try(() => JSON.stringify(result.values.sort())))
2 true ["unknown","west"]

MutableHashSet provides make, empty, and fromIterable, with in-place add, remove, and clear. Confine mutation to a single owner; mutable sets provide no concurrency coordination.

Balancing performance and persistence

function snapshots(values: ReadonlyArray<number>) {
  let current = HashSet.empty<number>()
  const history = [current]
  for (const value of values) {
    current = HashSet.add(current, value)
    history.push(current)
  }
  return history
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(snapshots([2, 2, 4]).map((set) => HashSet.size(set)))))
[0,1,1,2]

Persistent sets share internal nodes across updates, whereas mutable sets avoid allocation when prior snapshots are unnecessary. With well-distributed hashes, lookup, insertion, and removal run in near-constant average time, while traversals and set algebra scale with element count; poor custom hash functions degrade performance through collisions.

Converting to JavaScript collections

const regions = HashSet.make("west", "east")
const array = Array.from(regions)
const copy = [...regions]
const native = new Set(regions)
 
effect function report() {
  for (const region of Array.from(regions).sort()) try Console.log(region)
}
// Run in an effect function:
//   try Console.log(try Effect.try(() => JSON.stringify([array.sort(), copy.sort(), Array.from(native).sort()])))
//   try report()
[["east","west"],["east","west"],["east","west"]]
east
west

Both set types implement Iterable, supporting spread, Array.from, and for...of. Converting to a native Set switches to JavaScript equality semantics; avoid repeated array conversions inside hot loops.


The matching Effect page: effect.website/docs/v4/data-types/hash-set