I have a function that takes an array of objects, where each object contains a 'day' key (representing the day of the week) and an 'freeSlots' key (representing an array of available time slots as strings in 'h:mm a' format). The function aims to find and return the nearest valid free time slot from the current date and time. If no nearest slot is available for the current week, it should return "wait for next week." However, when searching for the nearest slot on Tuesday, the function is returning an unexpected result.
function findNearestFreeSlot(slotsArray) {
const currentDate = moment();
let nearestDayDiff = Infinity;
let nearestSlot = null;
for (const daySlots of slotsArray) {
const { day, freeSlots } = daySlots;
for (const slot of freeSlots) {
const slotDateTime = moment(slot, 'h:mm a').day(day);
// Check if the slot is on or after the current date
if (slotDateTime.isSameOrAfter(currentDate)) {
const diffDays = Math.abs(currentDate.diff(slotDateTime, 'days'));
if (diffDays < nearestDayDiff || (diffDays === nearestDayDiff && slotDateTime.isBefore(nearestSlot))) {
nearestDayDiff = diffDays;
nearestSlot = slotDateTime;
}
}
}
}
return nearestSlot ? nearestSlot.format('ddd, h:mm a') : "wait for next week";
}
I have used this array for testing the above function
const freeSlotsArray = [
{
day: 'wed',
freeSlots: ['12:00 pm', '1:00 pm', '1:30 pm', '2:30 pm', '3:00 pm', '3:30 pm', '4:30 pm', '5:00 pm', '6:30 pm', '7:00 pm']
},
{
day: 'sat',
freeSlots: ['7:00 am', '7:30 am', '8:00 am', '9:00 am', '10:00 am', '10:30 am', '11:30 am', '12:00 pm', '12:30 pm']
},
{
day: 'thu',
freeSlots: ['12:00 pm', '1:00 pm', '1:30 pm', '2:30 pm', '4:00 pm', '5:30 pm', '6:30 pm', '7:00 pm']
},
{
day: 'mon',
freeSlots: ['4:00 pm', '4:30 pm', '6:00 pm', '6:30 pm', '7:30 pm', '8:00 pm', '8:30 pm', '9:30 pm']
},
];
const nearestFreeSlot = findNearestFreeSlot(freeSlotsArray);
console.log(nearestFreeSlot);
When searching for the nearest slot on Tuesday, the expected output should be "Wed, 12:00 pm" instead of "Wed, 4:30 pm".