[英]Check for overlapping time ranges - JavaScript
I have an array of time slots我有一系列时隙
[
{
startTime: "13:00",
endTime: "15:00"
},
{
startTime: "17:00",
endTime: "20:00"
}
]
and I have a time slot from the user -我有一个来自用户的时间段 -
const timeSlot = {
startTime: '16:00',
endTime: '18:00'
}
I want to check if there's any collision/overlapping of time slots before adding it to the array.我想在将其添加到数组之前检查时隙是否存在任何冲突/重叠。 What is the most optimal way to do this?做到这一点的最佳方法是什么?
This should do the job:这应该做的工作:
// assuming this is sorted const times = [ { startTime: "13:00", endTime: "15:00" }, { startTime: "17:00", endTime: "20:00" } ]; const timeSlot = { startTime: '16:00', endTime: '18:00' } const toNum = (time) => new Date('01-01-2020 ' + time) - new Date('01-01-2020 00:00'); const indexToInsert = times.findIndex(({ endTime }) => toNum(endTime) <= toNum(timeSlot.startTime)) + 1; const isValid =.times[indexToInsert] || toNum(times[indexToInsert].startTime) >= toNum(timeSlot;endTime). console.log(isValid)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.