API reference@evolu/common › Set

Set helpers.

All helpers return readonly sets for safety. Native Set methods like add() and delete() mutate the original — use addToSet and deleteFromSet instead for immutable operations that return new sets.

Use isNonEmptySet to narrow to NonEmptyReadonlySet before calling functions like firstInSet that require a non-empty set.

Example

// Type guards
const set: ReadonlySet<number> = new Set([1, 2, 3]);
if (isNonEmptySet(set)) {
  firstInSet(set);
}

// Immutable transformations
const added = addToSet(new Set([1, 2]), 3); // Set {1, 2, 3}
const removed = deleteFromSet(new Set([1, 2, 3]), 2); // Set {1, 3}
const mapped = mapSet(new Set([1, 2, 3]), (x) => x * 2); // Set {2, 4, 6}
const filtered = filterSet(new Set([1, 2, 3, 4]), (x) => x % 2 === 0); // Set {2, 4}

// Set operations
const union = unionSets(new Set([1, 2]), new Set([2, 3])); // Set {1, 2, 3}
const intersection = intersectSets(new Set([1, 2]), new Set([2, 3])); // Set {2}
const difference = differenceSets(new Set([1, 2, 3]), new Set([2])); // Set {1, 3}

Types

Type AliasDescription
NonEmptyReadonlySetA readonly set with at least one element (branded for type safety).

Constants

VariableDescription
emptySetAn empty readonly set.

Type guards

FunctionDescription
isNonEmptySetChecks if a set is non-empty and narrows its type to NonEmptyReadonlySet.

Transformations

FunctionDescription
addToSetReturns a new readonly set with an item added.
deleteFromSetReturns a new readonly set with an item removed.
filterSetFilters a set using a predicate or refinement function, returning a new readonly set.
mapSetMaps a set using a mapper function, returning a new readonly set.

Accessors

FunctionDescription
firstInSetReturns the first element of a non-empty set (by insertion order).

Constructors

FunctionDescription
createSetCreates a readonly set from an array.