Interval Merge With Touching Ranges
Validate, sort and merge closed numeric intervals, combining overlapping and exactly touching ranges without mutating the input array.
Code
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;
}Inside the snippet
Interval Merge With Touching Ranges is built around the function mergeIntervals.
Iteration happens inside for (const [start, end] of normalized) — everything outside it runs once. Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.
The return value is newly constructed — inputs are never handed back.
Caveats
- The guard
start > endshort-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
The main signature reads export function mergeIntervals(intervals)
The surface worth importing is mergeIntervals; the helpers around it are private to the snippet.
Core lines
normalized.sort((left, right) => left[0] - right[0] || left[1] - right[1]);
if (!Array.isArray(intervals)) throw new TypeError("intervals must be an array");
throw new RangeError("interval start must not exceed end at index " + index);
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does `mergeIntervals` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- How does the code behave when input is bad?
- The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `mergeIntervals` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.