Any ideas to make it better or more efficient? any edge cases that are not covered? Opening times:
const openingTimes = [
{
date: "2020-01-01",
open: "08:00",
close: "18:00",
},
{
date: "2020-01-02",
open: "08:00",
close: "18:00",
},
{
date: "2020-01-03",
open: "08:00",
close: "18:00",
},
];
Booked Appointments (busy times):
const bookedAppointments = [
{
date: "2020-01-01",
time: "08:00",
},
{
date: "2020-01-01",
time: "11:00",
},
{
date: "2020-01-03",
time: "09:00",
},
{
date: "2020-01-03",
time: "10:00",
},
{
date: "2020-01-03",
time: "11:00",
},
];
Simple Solution:
const slot_duration = 60 * 60 * 1000;
const busyTimes = bookedAppointments.map((b) =>
Date.parse(`${b.date} ${b.time}`)
);
function isBusy(t) {
return busyTimes.some((b) => t >= b && t < b + slot_duration);
}
function getFreeSlots() {
const slots = {
free: [],
busy: [],
};
openingTimes.forEach((o) => {
const start = Date.parse(`${o.date} ${o.open}`);
const end = Date.parse(`${o.date} ${o.close}`);
for (let i = start; i <= end; i += slot_duration) {
if (isBusy(i)) {
slots.busy.push(new Date(i).toLocaleString());
} else {
slots.free.push(new Date(i).toLocaleString());
}
}
});
return slots;
}
time: "11:30"
. Explicitly sort Dates, and then exploit binary search or 2-way merge. [Hmm, bunch of recent edits to the OP.] \$\endgroup\$