JavaScript check if time ranges overlap

Viewed 18835

I have e.g. an array with 2 objects (myObject1 and myObject2 like ). Now when I add an third object I will check if time range overlaps. Actually I don't know how I can do this in a performant way.

var myObjectArray = [];

var myObject1 = {};
myObject1.startTime = '08:00';
myObject1.endTime = '12:30';
...

var myObject2 = {};
myObject2.startTime = '11:20';
myObject2.endTime = '18:30';
...

myObjectArray.push(myObject1);
myObjectArray.push(myObject2);
6 Answers

Let assume we have some intervals

const INTERVALS = [
  ['14:00', '15:00'],
  ['08:00', '12:30'],
  ['12:35', '12:36'],
  ['13:35', '13:50'],
];

If we want to add new interval to this list we should check if new interval is not overlapping with some of them.

You can loop trough intervals and check if the new one is overlapping with others. Note that when comparing intervals you do not need Date object if you are sure it is the same day as you can convert time to number:

function convertTimeToNumber(time) {
  const hours = Number(time.split(':')[0]);
  const minutes = Number(time.split(':')[1]) / 60;
  return hours + minutes;
}

There are two cases where intervals are NOT overlapping:

  1. Before (a < c && a < d) && (b < c && b <d):
a          b
|----------|
             c          d
             |----------| 
  1. After where (a > c && a > d) && (b > c && b > d):
             a          b
             |----------|
c          d
|----------| 

Because always c < d, it is enough to say that condition for NOT overlapping intervals is (a < c && b < c) || (a > d && b > d) and because always a < b, it is enough to say that this condition is equivalent to:

b < c || a > d

Negation of this condition should give us a condition for overlapping intervals. Base on De Morgan's laws it is:

b >= c && a <= d

Note that in both cases, intervals can not "touch" each other which means 5:00-8:00 and 8:00-9:00 will overlap. If you want to allow it the condition should be:

b > c && a < d

There are at least 5 situation of overlapping intervals to consider:

a          b
|----------|
      c          d
      |----------| 
      a          b
      |----------|
c          d
|----------| 
      a          b
      |----------|
c                    d
|--------------------|
a                    b
|--------------------|
      c          d
      |----------|
a          b
|----------|
c          d
|----------|

Full code with extra add and sort intervals functions is below:

    const INTERVALS = [
      ['14:00', '15:00'],
      ['08:00', '12:30'],
      ['12:35', '12:36'],
      ['13:35', '13:50'],
    ];


    function convertTimeToNumber(time) {
      const hours = Number(time.split(':')[0]);
      const minutes = Number(time.split(':')[1]) / 60;
      return hours + minutes;
    }

    // assuming current intervals do not overlap
    function sortIntervals(intervals) {
      return intervals.sort((intA, intB) => {
        const startA = convertTimeToNumber(intA[0]);
        const endA = convertTimeToNumber(intA[1]);

        const startB = convertTimeToNumber(intB[0]);
        const endB = convertTimeToNumber(intB[1]);

        if (startA > endB) {
          return 1
        }

        if (startB > endA) {
          return -1
        }

        return 0;
      })
    }


    function isOverlapping(intervals, newInterval) {
      const a = convertTimeToNumber(newInterval[0]);
      const b = convertTimeToNumber(newInterval[1]);

      for (const interval of intervals) {
        const c = convertTimeToNumber(interval[0]);
        const d = convertTimeToNumber(interval[1]);

        if (a < d && b > c) {
          console.log('This one overlap: ', newInterval);
          console.log('with interval: ', interval);
          console.log('----');
          return true;
        }
      }

      return false;
    }

    function isGoodInterval(interval) {
      let good = false;

      if (interval.length === 2) {
        // If you want you can also do extra check if this is the same day
        const start = convertTimeToNumber(interval[0]);
        const end = convertTimeToNumber(interval[1]);

        if (start < end) {
          good = true;
        }
      }

      return good;
    }

    function addInterval(interval) {
      if (!isGoodInterval(interval)) {
        console.log('This is not an interval');
        return;
      }

      if (!isOverlapping(INTERVALS, interval)) {
        INTERVALS.push(interval);

        // you may also want to keep those intervals sorted
        const sortedIntervals = sortIntervals(INTERVALS);
        console.log('Sorted intervals', sortedIntervals);
      }
    }


    // --------------------------------------
    const goodIntervals = [
      ['05:31', '06:32'],
      ['16:00', '17:00'],
      ['12:31', '12:34']
    ];

    let goodCount = 0;
    for (const goodInterval of goodIntervals) {
      if (!isOverlapping(INTERVALS, goodInterval)) {
        goodCount += 1
      }
    }

    console.log('Check good intervals: ', goodCount === goodIntervals.length);

    // --------------------------------------
    const ovelappingIntervals = [
      ['09:30', '12:40'],
      ['05:36', '08:50'],
      ['13:36', '13:37'],
      ['06:00', '20:00'],
      ['14:00', '15:00']
    ]

    let badCount = 0;
    for (const badInterval of ovelappingIntervals) {
      if (isOverlapping(INTERVALS, badInterval)) {
        badCount += 1
      }
    }

    console.log('Check bad intervals: ', badCount === ovelappingIntervals.length);

    // --------------------------------------
    addInterval(goodIntervals[0])

Here's something that might work.

// check if time overlaps with existing times
for (var j = 0; j < times.length; j++) {
        let existing_start_time = moment(this.parseDateTime(this.times[j].start_time)).format();
        let existing_end_time = moment(this.parseDateTime(this.times[j].end_time)).format();

        // check if start time is between start and end time of other times
        if (moment(start_time).isBetween(existing_start_time, existing_end_time)) {
            times[i].error = 'Time overlaps with another time';
            return false;
        }

        // check if end time is between start and end time of other times
        if (moment(end_time).isBetween(existing_start_time, existing_end_time)) {
            times[i].error = 'Time overlaps with another time';
            return false;
        }

}

https://momentjs.com/

You can check if there is an overlap by trying to merge a time range to the existing time ranges, if the total count of time ranges decrease after merge, then there is an overlap.

I found following articles which might help on handle merging ranges

Related