find available schedules from a list of schedules in javascript

To find the available schedules from a list of schedules in JavaScript, you can use the filter() method to filter out the schedules that are not available.

Let's assume that you have a list of schedules in an array with each item in the array representing a schedule as an object with start and end properties that are dates.

index.tsx
const schedules = [
  { start: new Date('2022-08-25T08:30:00'), end: new Date('2022-08-25T09:30:00') },
  { start: new Date('2022-08-25T10:00:00'), end: new Date('2022-08-25T11:00:00') },
  { start: new Date('2022-08-25T14:00:00'), end: new Date('2022-08-25T16:00:00') }
];
274 chars
6 lines

To find available schedules, you need to compare the existing schedules with the desired schedule to find whether there are overlaps. Here is a function to find available schedules:

index.tsx
function findAvailableSchedules(desiredSchedule, schedules) {
  return schedules.filter(schedule => {
    // check if the desired schedule overlaps with the current schedule
    if (desiredSchedule.start < schedule.end && schedule.start < desiredSchedule.end) {
      // if there is an overlap, the current schedule is not available
      return false;
    }
    // if there is no overlap, the current schedule is available
    return true;
  });
}
449 chars
12 lines

This function takes the desired schedule and the list of schedules as arguments and returns an array of available schedules. Here is an example of how to use it:

index.tsx
const desiredSchedule = { start: new Date('2022-08-25T12:00:00'), end: new Date('2022-08-25T13:00:00') };
const availableSchedules = findAvailableSchedules(desiredSchedule, schedules);
console.log(availableSchedules);
// output: [{ start: Wed Aug 25 2022 09:30:00 GMT+0300 (East Africa Time), end: Wed Aug 25 2022 10:00:00 GMT+0300 (East Africa Time) }, { start: Wed Aug 25 2022 11:00:00 GMT+0300 (East Africa Time), end: Wed Aug 25 2022 14:00:00 GMT+0300 (East Africa Time) }, { start: Wed Aug 25 2022 16:00:00 GMT+0300 (East Africa Time), end: Wed Aug 25 2022 23:59:59 GMT+0300 (East Africa Time) }]
602 chars
5 lines

In this example, we called the findAvailableSchedules() function with the desired schedule { start: new Date('2022-08-25T12:00:00'), end: new Date('2022-08-25T13:00:00') } and the list of schedules schedules. The function returned an array of available schedules, which were logged to the console.

gistlibby LogSnag