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.
Composing immutable and native operations
import {
addToSet,
assertEqual,
deleteFromSet,
filterSet,
firstInSet,
isNonEmptySet,
mapSet,
} from "@evolu/common";
const values = addToSet(new Set([1, 2]), 3);
const withoutOne = deleteFromSet(values, 1);
const doubled = mapSet(withoutOne, (x) => x * 2);
const atLeastFour = filterSet(doubled, (x) => x >= 4);
// Evolu's readonly results compose with native Set operations.
const union = atLeastFour.union(new Set([6, 8]));
const intersection = union.intersection(new Set([4, 6, 8, 10]));
const difference = intersection.difference(new Set([4]));
if (!isNonEmptySet(difference)) throw new Error("Expected values");
assertEqual(firstInSet(difference), 6);
Types
| Type Alias | Description |
|---|---|
| NonEmptyReadonlySet | A readonly set with at least one element (branded for type safety). |
Constants
| Variable | Description |
|---|---|
| emptySet | An empty readonly set. |
Constructors
| Function | Description |
|---|---|
| createSet | Creates a readonly set from an array. |
Type guards
| Function | Description |
|---|---|
| isNonEmptySet | Checks if a set is non-empty and narrows its type to NonEmptyReadonlySet. |
Transformations
| Function | Description |
|---|---|
| addToSet | Returns a new readonly set with an item added. |
| deleteFromSet | Returns a new readonly set with an item removed. |
| filterSet | Filters a set using a predicate or refinement function, returning a new readonly set. |
| mapSet | Maps a set using a mapper function, returning a new readonly set. |
Accessors
| Function | Description |
|---|---|
| firstInSet | Returns the first element of a non-empty set (by insertion order). |