// Plausible bug: validates with `new Date(s)` (which silently rolls 2023-02-29 over and accepts loose formats) and sorts the input in place.export type DateRange = { start: string; end: string };export type RangeErrorDetails = | { kind: "invalid_date"; index: number; value: string } | { kind: "inverted_range"; index: number };export class DateRangeError extends Error { public readonly kind: RangeErrorDetails["kind"]; constructor(details: RangeErrorDetails) { super(details.kind); this.kind = details.kind; Object.assign(this, details); }}const DAY = 86_400_000;const ms = (s: string): number => new Date(s).getTime();export function mergeRanges(ranges: DateRange[]): DateRange[] { ranges.forEach((r, index) => { if (Number.isNaN(ms(r.start))) throw new DateRangeError({ kind: "invalid_date", index, value: r.start }); if (Number.isNaN(ms(r.end))) throw new DateRangeError({ kind: "invalid_date", index, value: r.end }); if (ms(r.start) > ms(r.end)) throw new DateRangeError({ kind: "inverted_range", index }); }); ranges.sort((a, b) => ms(a.start) - ms(b.start)); const out: DateRange[] = []; for (const r of ranges) { const last = out[out.length - 1]; if (last && ms(r.start) <= ms(last.end) + DAY) { if (ms(r.end) > ms(last.end)) last.end = r.end; } else { out.push({ ...r }); } } return out;}