Checking for overlapping times JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of intervals (start and end time like this −

const arr = [
   { start: '01:00', end: '04:00' },
   { start: '05:00', end: '08:00' },
   { start: '07:00', end: '11:00' },
   { start: '09:30', end: '18:00' },
];

Our function should iterate through this array of objects and check all elements of the array against the others.

If an overlapping interval is found, the iteration stops and true is returned, Otherwise false. By overlapping intervals, we mean time intervals that have some time in common.

Example

const arr = [
   { start: '01:00', end: '04:00' },
   { start: '05:00', end: '08:00' },
   { start: '07:00', end: '11:00' },
   { start: '09:30', end: '18:00' },
];
const overlapping = (a, b) => {
   const getMinutes = s => {
      const p = s.split(':').map(Number);
      return p[0] * 60 + p[1];
   };
   return getMinutes(a.end) > getMinutes(b.start) && getMinutes(b.end) > getMinutes(a.start);
};
const isOverlapping = (arr) => {
   let i, j;
   for (i = 0; i < arr.length - 1; i++) {
       for (j = i + 1; j < arr.length; j++) {
         if (overlapping(arr[i], arr[j])) {
            return true;
         }
      };
   };
   return false;
};
console.log(isOverlapping(arr));

Output

And the output in the console will be −

true
raja
Published on 23-Nov-2020 11:11:35
Advertisements