Interval semantics and custom types
Discrete vs continuous (the “epsilon”)
Section titled “Discrete vs continuous (the “epsilon”)”Discreteness is a property of the domain, decided by whether it provides a
successor next (the “epsilon” / step). It is not a class hierarchy — see
Why composition, not inheritance.
Check at runtime with interval.isDiscrete (= domain.next !== undefined).
flowchart LR
DOM["IntervalDomain#lt;T#gt;"] --> NEXT{"provides next + prev?"}
NEXT -->|yes| DISC["discrete<br/>stored canonical [closed, open)<br/>length() counts elements<br/>[1,5] and [6,10] merge"]
NEXT -->|no| CONT["continuous<br/>bounds stored verbatim<br/>length() is a measure<br/>[1,5] and [6,10] leave a gap"]
| Continuous | Discrete | |
|---|---|---|
| You implement | compare (no next/prev) |
compare + next + prev |
| Adjacency | only exact touch + complementary closed ([a,b] & (b,c]) |
gap-free by step ([1,5] & [6,10]) |
| Stored bounds | verbatim | canonical [closed, open) (displayed as friendly [a,b]) |
length() |
a magnitude (measure) | element count |
| Built-ins | number, Date |
IntegerInterval, BigIntInterval |
IntegerInterval.closed(1, 5).union(IntegerInterval.closed(6, 10))?.toString(); // "[1,10]" (merge)NumberInterval.closed(1, 5).union(NumberInterval.closed(6, 10)); // null (gap)IntegerInterval.closed(1, 5).length(); // 5 (count of {1..5})NumberInterval.closed(1, 5).length(); // 4 (measure)IntegerInterval.closed(1, 5).isDiscrete; // trueNumberInterval.closed(1, 5).isDiscrete; // falseImplementing each:
import type { IntervalDomain } from "@xtandard/lib/interval";
// CONTINUOUS — just compare (+ optional measure/format/parse). No next/prev.const tempDomain: IntervalDomain<number> = { name: "celsius", compare: (a, b) => Math.sign(a - b), measure: (a, b) => b - a,};
// DISCRETE — also a true successor/predecessor (exactly one step, nothing between).const moneyDomain: IntervalDomain<number> = { name: "cents", compare: (a, b) => Math.sign(a - b), next: (v) => v + 1, // 1 cent prev: (v) => v - 1, measure: (a, b) => b - a,};Limitations / rules:
next/prevmust be a true successor/predecessor — exactly one step with no value in between, and consistent withcompare(next(v) > v). For floats this is not possible (Number.EPSILONis only the gap near 1.0; the ULP grows with magnitude), so leave floats continuous.- A domain is discrete or continuous — don’t provide
nextonly sometimes. - Discrete intervals are stored canonical
[closed, open);lower/upperreflect that (e.g.IntegerInterval.closed(1,5).upperis6open).toString()/length()hide this. Equality is canonical:(0,5] == [1,5]. - Mixing a continuous and a discrete domain of the same
T(e.g.NumberIntervalandIntegerInterval, bothInterval<number>) type-checks but is meaningless — operations use the receiver’s domain. Use one consistently.
Why composition, not inheritance
Section titled “Why composition, not inheritance”There is a single Interval<T> engine; the domain is injected (Guava’s Range<C> +
DiscreteDomain<C> model). We deliberately avoid an
Interval<T> → DiscreteInterval<T> → … hierarchy because:
- The same
Tcan be both —numberhas a continuous domain (numberDomain) and a discrete one (integerDomain). With inheritance you’d needNumberContinuousIntervalvsNumberDiscreteIntervalclasses; with a domain you just pick the domain. - New types need one object (
IntervalDomain<T>), not a new subclass + re-implemented operations. - All the set algebra lives once on
Interval<T>and works for every domain.
flowchart LR ND["numberDomain"] --> DT1["defineIntervalType"] --> NI["NumberInterval"] ID["integerDomain"] --> DT2["defineIntervalType"] --> II["IntegerInterval"] NI -->|extends| ENG["Interval#lt;number#gt;<br/>(one engine, one set algebra)"] II -->|extends| ENG
defineIntervalType(domain) still gives you a real new-able subclass per type for
ergonomics + instanceof, but discreteness rides on the domain, not the class.
Extended real line (±∞)
Section titled “Extended real line (±∞)”A domain may declare its infinity values (negativeInfinity/positiveInfinity). When
it does — only number among the built-ins (±Infinity) — the bracket on an
unbounded side is meaningful (the affinely extended real line ℝ̄):
NumberInterval.parse("[-Infinity,5]").contains(-Infinity); // trueNumberInterval.parse("(-Infinity,5]").contains(-Infinity); // falseNumberInterval.parse("[3,+Infinity]").contains(Infinity); // true// factories produce OPEN infinity:NumberInterval.atLeast(0).contains(Infinity); // false// set operations keep an included ±∞ unless the other side includes it too:NumberInterval.parse("[-Infinity,5]").difference(NumberInterval.closed(3, 4)).map(String);// ["[-Infinity,3)", "(4,5]"]NumberInterval.parse("[-Infinity,5]").difference(NumberInterval.atMost(0)).map(String);// ["[-Infinity,-Infinity]", "(0,5]"]: atMost(0) is open at -∞, so the point -∞ remainsDomains without an infinity value (Date, bigint, Instant, …) have no ±∞
element, so an unbounded side is always open — [-Infinity,…] normalizes to (-Infinity,…).
Edge cases
Section titled “Edge cases”number:contains(NaN)→false(not comparable);parse("[NaN,5]")/parse("[lala,5]")→ throws. Ordering is exact, butlength()/middle()/formatinherit IEEE-754 fuzz ([0.1,0.3].length()→0.19999999999999998) — for exact decimals useDecimalIntervalor an integer-backed domain.Date:contains(new Date("lala"))→false(Invalid Date);parseof an invalid date string → throws.Temporal: there is no “Invalid Instant” sentinel —Temporal.Instant.from("lala")throws, so an invalid value can never be constructed or queried.
instanceof & element-type safety
Section titled “instanceof & element-type safety”Instances are instanceof both the bound class and Interval. Operations return base
Interval<T> (still instanceof Interval). The element type T isolates types — a
NumberInterval cannot union an InstantInterval (compile error).
const r = NumberInterval.closed(0, 5);r instanceof NumberInterval; // truer instanceof Interval; // trueCustom types
Section titled “Custom types”Unlike Guava (which requires T extends Comparable), you inject the ordering via an
IntervalDomain<T>, then bind it with defineIntervalType. The minimum is name +
compare (one comparator subsumes eq/lt/gt). Everything else is optional:
| Hook | Enables |
|---|---|
compare(a, b) (required) |
ordering — contains, all set ops |
next / prev |
discrete domain → adjacency / merge (the “epsilon”) |
measure(lower, upper) |
length() |
add(value, delta) |
fromStart / fromEnd / fromCenter / middle |
format / parse |
toString() / parseInterval |
isValid(value) |
reject invalid members (NaN, Invalid Date) |
negativeInfinity / positiveInfinity |
includable ±∞ (extended line) |
import { defineIntervalType, type IntervalDomain } from "@xtandard/lib/interval";import { dinero, lessThan, greaterThan, toSnapshot, type Dinero } from "dinero.js";
const dineroDomain: IntervalDomain<Dinero<number>> = { name: "dinero", compare: (a, b) => (lessThan(a, b) ? -1 : greaterThan(a, b) ? 1 : 0), measure: (a, b) => toSnapshot(b).amount - toSnapshot(a).amount, // optional};
const DineroInterval = defineIntervalType(dineroDomain);type DineroInterval = InstanceType<typeof DineroInterval>;
const millionaire = DineroInterval.atLeast(usd(100_000_000)); // [$1,000,000.00, +Infinity)const isMillionaire = (cash: Dinero<number>) => millionaire.contains(cash);Notes on the “step” (next/prev): integer/bigint use +1/+1n; money could be
+1 minor unit (discrete → adjacent ranges merge). Floats and instants are kept
continuous on purpose (no true successor — float ULP grows with magnitude, and
[1,5] ∪ [6,10] should stay a gap), so add a step only when you want discrete merge.