Skip to content

Interval domains

@xtandard/lib/temporal ships the engine bound to the TC39 Temporal types (peer dependency @js-temporal/polyfill):

Class Element T Kind
InstantInterval Temporal.Instant continuous
ZonedDateTimeInterval Temporal.ZonedDateTime continuous
PlainDateInterval Temporal.PlainDate discrete (ε 1 day)
PlainDateTimeInterval Temporal.PlainDateTime continuous
PlainTimeInterval Temporal.PlainTime continuous

The matching domains (instantDomain, zonedDateTimeDomain, …) are exported too, for use with defineIntervalType or parseInterval.

import { PlainDateInterval, InstantInterval } from "@xtandard/lib/temporal";
import { Temporal } from "@js-temporal/polyfill";
// Discrete calendar days merge gap-free:
PlainDateInterval.closed(
Temporal.PlainDate.from("2026-01-01"),
Temporal.PlainDate.from("2026-01-05"),
)
.union(
PlainDateInterval.closed(
Temporal.PlainDate.from("2026-01-06"),
Temporal.PlainDate.from("2026-01-10"),
),
)
?.toString(); // "[2026-01-01,2026-01-10]"
InstantInterval.parse("[2026-01-01T00:00:00Z,2026-01-02T00:00:00Z)").length(); // 86_400_000 (ms)

Precision. Ordering, membership (contains), set operations, and parse/format are exact — compare defers to Temporal.*.compare (nanosecond-precise for Instant/ZonedDateTime) and the string form is round-trippable ISO. Only length() / middle() / fromStart work in milliseconds (days for PlainDate), because the engine types measure/add as a JS number and epoch nanoseconds overflow Number.MAX_SAFE_INTEGER after ~104 days; milliseconds keep length() an exact integer for ~285,000 years. For sub-millisecond spans, subtract the endpoints’ epochNanoseconds (a bigint) directly.

The domains never use instanceof Temporal.* (only static compare/from and instance methods), so values from any TC39-compatible polyfill order correctly.

@xtandard/lib/decimal binds the engine to decimal.js Decimal values (peer dependency decimal.js) — an exact, continuous alternative to NumberInterval for when IEEE-754 float fuzz is unacceptable:

import { DecimalInterval } from "@xtandard/lib/decimal";
import { Decimal } from "decimal.js";
const d = (s: string) => new Decimal(s);
// number leaks the representation error; decimal does not:
NumberInterval.closed(0.1, 0.3).length(); // 0.19999999999999998
DecimalInterval.closed(d("0.1"), d("0.3")).length(); // 0.2
DecimalInterval.closed(d("0.1"), d("0.3")).toString(); // "[0.1,0.3]"
DecimalInterval.parse("[1.000000000000000000000000000001,2]"); // 30 sig digits preserved

CONTINUOUS — decimals are dense, so there is no successor (isDiscrete is false). compare, contains, set operations, and toString/parse are exact arbitrary-precision. Only measure/length()/middle() round-trip through a JS number (the engine’s measure return type) — but the value is computed exactly first, so clean decimals report cleanly. Members must be finite (NaN/±Infinity are rejected by contains).

Same model, different backing library — pick the one you already use; the API and behavior are identical:

Entry Class Peer dep Notes
@xtandard/lib/decimal DecimalInterval decimal.js Most full-featured (irrational ops)
@xtandard/lib/big BigInterval big.js Smallest footprint; always finite
@xtandard/lib/bignumber BigNumberInterval bignumber.js Base conversion; common in finance

Each entry also exports its bare domain (decimalDomain, bigDomain, bigNumberDomain) for parseInterval, mergeIntervals, or your own defineIntervalType class:

import Big from "big.js";
import { mergeIntervals, parseInterval } from "@xtandard/lib/interval";
import { BigInterval, bigDomain } from "@xtandard/lib/big";
parseInterval(bigDomain, "[1.5,2.5]").toString(); // "[1.5,2.5]"
mergeIntervals(bigDomain, [
BigInterval.closed(new Big("0"), new Big("0.5")),
BigInterval.closed(new Big("0.5"), new Big("1")),
]).map(String); // ["[0,1]"]

@xtandard/lib/fraction binds the engine to fraction.js Fraction values (peer dependency fraction.js) — exact rationals. Unlike the decimal libraries, 1/3 is represented losslessly (it has no finite decimal expansion) and the string form is "1/3":

import { FractionInterval } from "@xtandard/lib/fraction";
import Fraction from "fraction.js";
const third = (n: number) => new Fraction(n, 3);
FractionInterval.closed(third(1), third(2)).toString(); // "[1/3,2/3]"
FractionInterval.closed(third(1), third(2)).contains(new Fraction(1, 2)); // true
FractionInterval.parse("[1/3,2/3]").toString(); // "[1/3,2/3]" (round-trips, exact)

CONTINUOUS (rationals are dense). compare, contains, and the "n/d" string form are exact rationals; measure/length()/middle() round-trip through a JS number (so a length is a floating-point magnitude even though the endpoints stay exact): FractionInterval.closed(third(1), third(2)).length() is 0.3333333333333333. fractionDomain is exported too, for parseInterval/mergeIntervals/defineIntervalType.

@xtandard/lib/dinero binds the engine to dinero.js v2 values (peer dependency dinero.js). Money is discrete: the epsilon is one minor unit at the currency’s standard exponent (1 cent for USD, 1 whole yen for JPY), so adjacent ranges merge gap-free and length() counts representable amounts.

Because a Dinero value carries its currency, an interval is bound to one currency — build a class with createDineroInterval(currency):

import { createDineroInterval } from "@xtandard/lib/dinero";
import { dinero, USD } from "dinero.js";
const UsdInterval = createDineroInterval(USD);
const usd = (cents: number) => dinero({ amount: cents, currency: USD });
const tier = UsdInterval.closed(usd(5_000), usd(10_000)); // $50.00 – $100.00
tier.contains(usd(7_500)); // true
tier.length(); // 5001 (cents $50.00..$100.00 inclusive)
tier.toString(); // "[5000,10000]" (minor units)
// epsilon-adjacent ranges merge:
UsdInterval.closed(usd(100), usd(105))
.union(UsdInterval.closed(usd(106), usd(110)))
?.toString(); // "[100,110]"

The string form (and parse) is the currency’s minor units (integer). dineroDomain(currency) is exported too, for use with defineIntervalType/parseInterval.

Precision. compare defers to dinero’s own (scale-aware, exact) comparison, so a value carrying sub-minor-unit precision (a larger scale, e.g. $1.2345) is still ordered/contained exactly. Stepping (next/prev), measure/length(), and the string form work on the whole-minor-unit grid — a sub-cent value is half-even rounded to cents there. Use whole minor units for predictable discrete behavior.

StringInterval (in @xtandard/lib/interval, zero-dep) orders strings lexicographically (UTF-16 code-unit order — deterministic, not locale-aware). CONTINUOUS: no successor and no length(). Useful for keyspace/shard partitioning, prefix scans, and geohash spatial ranges (geohashes sort lexicographically).

import { StringInterval } from "@xtandard/lib/interval";
StringInterval.closedOpen("a", "n").contains("mango"); // true
// idiomatic prefix scan: [prefix, prefix + '￿')
StringInterval.closedOpen("user:", "user:￿").contains("user:42"); // true

The [a,b] string form splits on the FIRST comma, so values containing ,/[/]/(/) are not round-trippable through parse/toString (every other operation is unaffected).

createOrdinalInterval(labels) (in @xtandard/lib/interval, zero-dep) builds a DISCRETE class over an ordered list of string labels — a small “enum” (sizes, priority/log levels). Ordering is list position, so adjacent labels merge and length() counts labels. The interval operates on the label index; .index(label) / .label(i) convert, and toString()/parse() use the labels.

import { createOrdinalInterval } from "@xtandard/lib/interval";
const Size = createOrdinalInterval(["XS", "S", "M", "L", "XL"]);
const r = Size.closed(Size.index("S"), Size.index("L"));
r.toString(); // "[S,L]"
r.length(); // 3 ({S, M, L})
r.contains(Size.index("M")); // true

@xtandard/lib/semver binds the engine to semver version strings (peer dependency semver) — a version range is an interval. Useful for compatibility windows, “affected versions” in advisories, and release gates.

import { SemverInterval } from "@xtandard/lib/semver";
const compatible = SemverInterval.closedOpen("1.2.0", "2.0.0"); // [1.2.0, 2.0.0)
compatible.contains("1.5.3"); // true
compatible.contains("2.0.0"); // false
compatible.contains("1.0.0-rc.1"); // false (prerelease sorts below its release)

CONTINUOUS — prereleases (1.0.0-rc.1 < 1.0.0) mean no clean successor, so there’s no length()/middle(). Ordering and membership use semver precedence; members must be valid semver (parse normalizes and rejects invalid versions). semverDomain is exported for use with defineIntervalType/parseInterval.

Membership is plain semver precedence, not npm range matching. A prerelease of the upper bound sorts below it, so it is inside a half-open range, while npm’s >=1.2.0 <2.0.0 excludes prereleases by default:

compatible.contains("2.0.0-rc.1"); // true (2.0.0-rc.1 < 2.0.0)
// semver.satisfies("2.0.0-rc.1", ">=1.2.0 <2.0.0") → false

To keep the upper bound’s prereleases out, end at 2.0.0-0, the lowest possible prerelease: SemverInterval.closedOpen("1.2.0", "2.0.0-0").contains("2.0.0-rc.1") is false. Prereleases of versions inside the range (1.5.0-beta.1) are still members; filter them yourself if you need npm’s full rules.

@xtandard/lib/ip binds the engine to IPv4/IPv6 addresses via ipaddr.js (peer dependency). DISCRETE (ε = one address), so a CIDR block is a clean range, adjacent ranges merge, and length() counts addresses. Useful for firewall rules, allowlists, CIDR math, and geo-IP buckets.

import { Ipv4Interval, Ipv6Interval } from "@xtandard/lib/ip";
const lan = Ipv4Interval.cidr("192.168.0.0/16"); // or .closed(Ipv4Interval.ip("192.168.0.0"), …)
lan.contains(Ipv4Interval.ip("192.168.1.50")); // true
lan.length(); // 65536
lan.toString(); // "[192.168.0.0,192.168.255.255]"
Ipv6Interval.cidr("2001:db8::/32").contains(Ipv6Interval.ip("2001:db8::1")); // true

Addresses are modeled as their integer value (bigint) so arithmetic never overflows the address space; toString() renders the canonical dotted (v4) / compressed (v6) form. Build from a string with .ip(addr) or from a block with .cidr(block). Ipv4Interval and Ipv6Interval are also types (the instance type), and all the set operations work on address ranges:

Ipv4Interval.ip("10.0.0.1"); // 167772161n
Ipv4Interval.cidr("10.0.0.0/25").union(Ipv4Interval.cidr("10.0.0.128/25"))?.toString();
// "[10.0.0.0,10.0.0.255]" (adjacent blocks merge)
Ipv4Interval.cidr("10.0.0.0/24").difference(Ipv4Interval.cidr("10.0.0.64/26")).map(String);
// ["[10.0.0.0,10.0.0.63]", "[10.0.0.128,10.0.0.255]"]

length() is a JS number, so it is exact up to 2^53 addresses; a large IPv6 block (/32 has 2^96) reports an approximate count.