我有一个函数,它接受一个对象数组,其中每个对象包含一个'day'键(表示一周中的哪一天)和一个'freeSlots'键(以'h:mm a'格式的字符串表示可用时隙数组)。该函数的目的是查找并返回距离当前日期和时间最近的有效空闲时隙。如果当前周没有最近的插槽可用,则它应返回“wait for next week”。但是,当搜索周二的最近插槽时,该函数返回意外结果。
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";
}
字符串
我用这个数组来测试上面的函数
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);
型
在星期二搜索最近的时间段时,预期的输出应该是“Wed,12:00pm”而不是“Wed,4:30pm”。
1条答案
按热度按时间6ju8rftf1#
问题是您向
.day()
传递了一个错误的参数,传递了一个从0到6的数字(或者是当天的全名,但我不确定这个替代方案的效果如何)。下面我把一个更紧凑的函数和你正确的一个。
个字符