Interval Merge With Touching Ranges

Validate, sort and merge closed numeric intervals, combining overlapping and exactly touching ranges without mutating the input array.

JavascriptData Integrity

Code

snippet
export function mergeIntervals(intervals) {
  if (!Array.isArray(intervals)) throw new TypeError("intervals must be an array");
  const normalized = intervals.map((interval, index) => {
    if (!Array.isArray(interval) || interval.length !== 2) {
      throw new TypeError("interval at index " + index + " must be [start, end]");
    }
    const [start, end] = interval;
    if (!Number.isFinite(start) || !Number.isFinite(end)) {
      throw new TypeError("interval bounds must be finite numbers");
    }
    if (start > end) {
      throw new RangeError("interval start must not exceed end at index " + index);
    }
    return [start, end];
  });

  normalized.sort((left, right) => left[0] - right[0] || left[1] - right[1]);
  const merged = [];
  for (const [start, end] of normalized) {
    const last = merged[merged.length - 1];
    if (last && start <= last[1]) {
      last[1] = Math.max(last[1], end);
    } else {
      merged.push([start, end]);
    }
  }
  return merged;
}