1

I have a page where we can add available time slots for a given item. These time slots can be added to any order, but a selected slot should not overlap with other slots. So, before I save I need to validate all the added time slots are overlapping or not with each other. My plan is to add two forloops for this. But I'm wondering there is another way of doing this more efficiently with less coding. Please share your thoughts on this.

In the given image 09:00 - 11:00 is overlapping with 08:00 - 10:00. So it should not allow saving.

I'm trying to add a for loop like below which is not completed. I wonder there is another way of doing this easily.

    function isAnOverlapEvent (inputs) {
    var i;
    var matchingList;

    for (i = 0; i < inputs.length; i++) {
        var item = inputs[i];
        matchingList = inputs;

        matchingList.splice(item.index, 1);

        for (k = 0; k < matchingList.length; k++) {
            
        }                
    }
    return false;
}

Can someone help me with this?

user2837480
  • 349
  • 2
  • 18
  • 1
    Can you provide the structure of `inputs` and some sample data? Also how are you persisting the existing timeslots? – Tom O. Mar 15 '21 at 15:51

1 Answers1

2

Long story short, when a timeslot is added you should compare it to the timeslots that already exist and make sure that it ends before the start of each existing timeslot, or that it starts after the end of existing timeslots.

If you want more details on date (or time) comparison, you can read this very detailed answer.

const existingTimeslots = [{start: 8, end: 10}, {start: 12, end: 14}, {start: 14, end: 16}];

const isNewSlotValid = (newSlot) => {
  let isValid = true;
  
  for(let i = 0; i < existingTimeslots.length; i++) {
    if((existingTimeslots[i].end > newSlot.start) && (existingTimeslots[i].end <= newSlot.end)) {
      isValid = false;
    }
  }
  
  return isValid;
}

console.log(isNewSlotValid({start: 9, end: 11})); // Should return false
console.log(isNewSlotValid({start: 16, end: 18})); // Should return true
Romain biard
  • 186
  • 9
  • Thanks for the answer. If we adding a new slot at a time and saving it then it's fine. What if the users can update previously added slots as well? As an example, they can update 08:00-10:00 to 07:00-11:00 if they want to. But in the end, overall added slots should not be overlapped. That's why I thought of using two for loops. Take one slot and checking it with all other slots. – user2837480 Mar 15 '21 at 17:55
  • In this scenario, I think that you could create a new function, isUpdatedSlotValid that would take 2 parameters: the new slot, and the list of slots without the one that is being updated by the user. It should work the same way that the isNewSlotValid function. – Romain biard Mar 16 '21 at 10:08