Skip to content

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; // true
NumberInterval.closed(1, 5).isDiscrete; // false

Implementing 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/prev must be a true successor/predecessor — exactly one step with no value in between, and consistent with compare (next(v) > v). For floats this is not possible (Number.EPSILON is only the gap near 1.0; the ULP grows with magnitude), so leave floats continuous.
  • A domain is discrete or continuous — don’t provide next only sometimes.
  • Discrete intervals are stored canonical [closed, open); lower/upper reflect that (e.g. IntegerInterval.closed(1,5).upper is 6 open). toString()/length() hide this. Equality is canonical: (0,5] == [1,5].
  • Mixing a continuous and a discrete domain of the same T (e.g. NumberInterval and IntegerInterval, both Interval<number>) type-checks but is meaningless — operations use the receiver’s domain. Use one consistently.

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 T can be both — number has a continuous domain (numberDomain) and a discrete one (integerDomain). With inheritance you’d need NumberContinuousInterval vs NumberDiscreteInterval classes; 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.

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); // true
NumberInterval.parse("(-Infinity,5]").contains(-Infinity); // false
NumberInterval.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 -∞ remains

Domains without an infinity value (Date, bigint, Instant, …) have no ±∞ element, so an unbounded side is always open — [-Infinity,…] normalizes to (-Infinity,…).

  • number: contains(NaN) → false (not comparable); parse("[NaN,5]") / parse("[lala,5]") → throws. Ordering is exact, but length()/middle()/format inherit IEEE-754 fuzz ([0.1,0.3].length() → 0.19999999999999998) — for exact decimals use DecimalInterval or an integer-backed domain.
  • Date: contains(new Date("lala")) → false (Invalid Date); parse of 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.

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; // true
r instanceof Interval; // true

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.