Skip to content
Standard library

Set#

Set is a global, as in Node; import { Set } from "velt/collections" names the same class. An insertion-ordered hash set with JavaScript Set semantics plus the ES2025 set algebra. It is built on the prelude's Map, so elements compare as map keys do: numbers, bool and strings by value, objects (class instances, object types, arrays) by identity, as in JavaScript, structs (Velt value types) by content, and tuples part by part.

ts
const seen = new Set(["a", "b", "a", "c"]);
seen.add("d");
const other = Set.from(["c", "d", "e"]);
console.log(seen.size, seen.has("b"), seen.values()); // 4 true [ 'a', 'b', 'c', 'd' ]
console.log(seen.intersection(other).values(), seen.difference(other).values()); // [ 'c', 'd' ] [ 'a', 'b' ]
console.log(seen.union(other).size, other.isSubsetOf(seen), seen.delete("a")); // 5 false true
console.log(seen); // Set(3) { 'b', 'c', 'd' }
  • new Set<T>(), new Set(values) (leaves values as it is and shares the elements, like JavaScript; values may be any iterable, new Set(gen())), Set.from(xs) (the same as new Set(xs)), size, isEmpty().
  • add(v) takes ownership of v. has(v), delete(v): bool, clear().
  • values(): T[] returns the elements in insertion order (objects are shared, not copied). forEach(f) borrows them.
  • A set is an Iterable<T>: for (const x of s) visits its elements in insertion order. s[Symbol.iterator]() iterates the elements as of the call (JavaScript's set iterator is a live view).
  • Set algebra, each returning a new set that holds the elements themselves (objects are shared, as in JavaScript): union, intersection, difference, symmetricDifference.
  • Tests: isSubsetOf, isSupersetOf, isDisjointFrom.
  • console.log(s) prints a set as Node does: Set(2) { 'a', 'b' } (empty: Set(0) {}), the first 100 elements followed by ... n more items.

ReadonlySet<T> is TypeScript's: a Set<T> that a variable or parameter declared with this type may not change (add, delete and clear are errors through it).

Edit this page on GitHub