JSFiddle - React, Tailwind, and code Playground

by roskoshinsky

JavaScript

const mergeRanges = (...ranges) => ranges
	.sort((a, b) => a[0] - b[0])
    .reduce((acc, v, i, arr) => {
    	const lastRange = acc.pop() ?? [];
        if (lastRange[0] === undefined) {
	        acc.push(v);
            return acc;
        }
        if (v[0] <= lastRange[1]) {
        	if (v[1] > lastRange[1]) {
	            acc.push([lastRange[0], v[1]]);
            	return acc;
            }
	        acc.push([lastRange[0], lastRange[1]]);
            return acc;
        }
        acc.push(lastRange, v);
        return acc;
    }, []);

console.log(mergeRanges([1, 3], [100, 200], [2, 4]));

console.log(mergeRanges([1, 3], [100, 200], [150, 170], [2, 4]));

console.log(mergeRanges([1, 3], [100, 200], [150, 170], [2, 4], [0, 1000]));

console.log(mergeRanges(
    [1, 3],
    [13, 104],
    [100, 200],
    [10, 16],
    [2, 4],
    [4, 9],
));