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 Alias | Description |
|---|---|
| NonEmptyReadonlySet | A readonly set with at least one element (branded for type safety). |
Constants
| Variable | Description |
|---|---|
| emptySet | An empty readonly set. |
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). |
Constructors
| Function | Description |
|---|---|
| createSet | Creates a readonly set from an array. |