mergeIntervals
Signature
Section titled “Signature”mergeIntervals(intervals: Interval[]): Interval[]Collapse a list of half-open intervals into the fewest sorted, non-overlapping intervals.
- Overlapping and touching intervals (
a.endisb.start) coalesce:[09, 12) ∪ [12, 17)is[09, 17). Intervals one nanosecond apart do not. - Input order does not matter; the result is sorted by start, and no two results touch.
- Empty intervals (
start === end) cover no time: one that touches or lies inside a run is absorbed, one that touches nothing is dropped (GMT rule). - Endpoints are the caller’s own strings. A run keeps the start of its first interval (by instant, then input order) and the end of the first interval to reach its latest end (GMT rule: first wins ties between spellings of one instant).
[]is both a legitimate result (an empty list, or a list of only empty intervals) and the invalid-input sentinel; check inputs withisValidIntervalwhen the difference matters.- The positional
mergeIntervalsUtc,mergeIntervalsZoned(…) follow the same half-open rule and re-serialise endpoints instead of echoing the caller’s strings. - Returns
[]whenintervalsis not an array or any element is not a validInterval.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
intervals | Interval[] | array of { start, end } records of ISO 8601 instant strings |
Returns
Section titled “Returns”sorted, disjoint, non-touching { start, end } records, or [] on invalid input
Related types
Section titled “Related types”Examples
Section titled “Examples”import { mergeIntervals } from "@northguild/gmt/interval/calculate";
mergeIntervals([{ start: "2024-01-01T13:00:00Z", end: "2024-01-01T17:00:00Z" }, { start: "2024-01-01T09:00:00Z", end: "2024-01-01T12:00:00Z" }]) // [{ start: "2024-01-01T09:00:00Z", end: "2024-01-01T12:00:00Z" }, { start: "2024-01-01T13:00:00Z", end: "2024-01-01T17:00:00Z" }]