@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
50 lines (48 loc) • 2.65 kB
JavaScript
import { isObject } from "../../internal/isObject.js";
import { coalesceIntervalNanoseconds } from "../../internal/intervalNanoseconds.js";
import { utcIntervalRecordOf } from "../../internal/intervalChecks.js";
// src/utc/interval/mergeIntervalsUtc.ts
/**
* Collapse a list of UTC intervals into the minimum set of non-overlapping intervals.
*
* - List-form generalization of `intervalUnionUtc`, which is pairwise only.
* - Half-open: an interval holds every `t` with `start <= t < end`. Overlapping intervals and
* touching intervals (`aEnd === bStart`) join into one run; any gap, even one unit, keeps them
* apart (CORE-6's `mergeIntervals`).
* - An empty interval (`start === end`) holds nothing: it is absorbed by a run it touches or lies
* in, and dropped otherwise, so every returned interval is non-empty.
* - Delegates to CORE-6's `mergeIntervals` once every element passes the UTC-string gate, and
* re-serialises the runs to canonical `Z` strings.
* - Order of the input list does not matter; the result is sorted by start.
* - Returns `[]` for an empty list.
* - Returns `[]` when `intervals` is not an array, when any element is not a
* `{ start, end }` record of valid ISO UTC datetime strings, or when any element has
* `start > end` or a leap-second string.
*
* @param intervals array of `{ start, end }` records
* @returns the minimum set of non-overlapping `{ start, end }` records, sorted by start, or `[]` on invalid input
*
* @example mergeIntervalsUtc([{ start: "2024-01-01T00:00:00Z", end: "2024-01-10T00:00:00Z" }, { start: "2024-01-05T00:00:00Z", end: "2024-01-15T00:00:00Z" }]) // [{ start: "2024-01-01T00:00:00Z", end: "2024-01-15T00:00:00Z" }]
* @example mergeIntervalsUtc([{ start: "2024-01-01T09:00:00Z", end: "2024-01-01T12:00:00Z" }, { start: "2024-01-01T12:00:00Z", end: "2024-01-01T17:00:00Z" }]) // [{ start: "2024-01-01T09:00:00Z", end: "2024-01-01T17:00:00Z" }] (touching)
* @example mergeIntervalsUtc([{ start: "2024-01-01T09:00:00Z", end: "2024-01-01T09:00:00Z" }]) // [] (empty interval)
* @example mergeIntervalsUtc([]) // []
*/
function mergeIntervalsUtc(intervals) {
try {
if (!Array.isArray(intervals) || intervals.length === 0) return [];
const records = [];
for (let index = 0; index < intervals.length; index++) {
const interval = intervals[index];
const record = isObject(interval) ? utcIntervalRecordOf(interval.start, interval.end) : null;
if (record === null) return [];
records.push(record);
}
return coalesceIntervalNanoseconds(records).map((run) => ({
start: run.startText,
end: run.endText
}));
} catch {
return [];
}
}
export { mergeIntervalsUtc };