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 AliasDescription
NonEmptyReadonlySetA readonly set with at least one element (branded for type safety).

Constants

VariableDescription
emptySetAn empty readonly set.

Constructors

FunctionDescription
createSetCreates a readonly set from an array.

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).