Check for overlapping time ranges - JavaScript

Viewed 44

I have an array of time slots

[
      {
        startTime: "13:00",
        endTime: "15:00"
      },
      {
        startTime: "17:00",
        endTime: "20:00"
      }
]

and I have a time slot from the user -

const timeSlot = {
  startTime: '16:00',
  endTime: '18:00'
}

I want to check if there's any collision/overlapping of time slots before adding it to the array. What is the most optimal way to do this?

1 Answers

This should do the job:

// assuming this is sorted
const times = [
  {
    startTime: "13:00",
    endTime: "15:00"
  },
  {
    startTime: "17:00",
    endTime: "20:00"
  }
];

// given timeSlot by the user
const timeSlot = {
  startTime: '16:00',
  endTime: '18:00'
}

// function to transform the given time to the minutes of a day
const toMin = (time) => {
    const [hours, minutes] = time.split(':');
    return Number(hours) * 60 + Number(minutes);
};

// find the index of the time where the given time could be inserted
const indexToInsert = times.findIndex(({ endTime }) => toMin(endTime) <= toMin(timeSlot.startTime)) + 1;

// check wether the next startTime allows adding the given timeSlot
const isValid = !times[indexToInsert] || toMin(times[indexToInsert].startTime) >= toMin(timeSlot.endTime);

console.log(isValid)

Related