JSFiddle - React, Tailwind, and code Playground

by Eugen Sunic

JavaScript

/* const list = [
  [1, 3],
  [2, 6],
  [8, 10],
  [15, 18]
];
 */



var merge = function(intervals) {
  if (intervals.length === 0 || intervals.length === 1) return intervals

  function isOverlap(a, b) {
    const [min1, max1] = a
    const [min2, max2] = b
    if ((max1 >= min2 && max1 <= max2) || (max2 >= min1 && max2 <= max1)) {
      return true;
    }
    return false;
  }

  const sorted = intervals.sort((a, b) => a[0] - b[0]);
  const result = [];
  let i = 0;

  while (i < sorted.length) {
	console.log('went')
    if (isOverlap(sorted[i], sorted[i + 1])) {
      const [min] = sorted[i];
      const [max] = sorted[i + 1];
      result.push(min, max);
      i++;
    } else if (isOverlap(result[result.length - 1], sorted[i])) {
      const refPair = result[result.length - 1][1] = sorted[i][1];
    }
    i++;
  }
	return result;
}



/* console.log(merge([
  [1, 4],
  [4, 5]
]));
console.log(merge([
  [1, 4],
  [5, 6]
]));
 */
console.log(merge([
  [1, 3],
  [2, 6],
  [8, 10],
  [15, 18]
]));

/* console.log(merge([
  [1, 4],
  [2, 3]
]));
 */
// res [[0,5]]
/* [
  [0, 2],
  [1, 4],
  [3, 5]
]
 */
console.log(merge([
  [0, 2],
  [1, 4],
  [3, 5]
]));