判断如下时间是否有交集
const time = [
{
startTime: "17:31",
endTime: "17:35"
},
{
startTime: "17:35",
endTime: "17:39"
},
{
startTime: "18:00",
endTime: "18:39"
},
{
startTime: "19:35",
endTime: "19:39"
}
]
const date = [
{
startDate: "2019-08-14",
endDate: "2019-08-17"
},
{
startDate: "2019-08-17",
endDate: "2019-08-20"
}
]
判断交集的方法
const check = (a,b,x,y) => {
if(y<a||b<x){
return false;
}else{
return true;
}
}
const checkTime = (a,b,x,y) => {
let times1=[];
let times2 = [];
if (a<b) {
//未跨天
times1.push([a,b]);
}else{
//跨天
times1.push([a,"24:00"],["00:00",b]);
}
if (x<y) {
times2.push([x,y]);
}else{
times2.push([x,"24:00"],["00:00",y]);
}
let flag = false;
//循环比较时间段是否冲突
for (let i = 0; i < times1.length; i++) {
if (flag) break;
for (let j = 0; j < times2.length; j++) {
if(check(times1[i][0],times1[i][1],times2[j][0],times2[j][1])){
flag = true;
break;
}
}
}
if (flag) {
return {
flag,
msg:`发生冲突: ${times1[0][0]}-${times1[0][1]} 与 ${times2[0][0]}-${times2[0][1]}`
};
}else{
return {
flag,
msg:`发生冲突: ${times1[0][0]}-${times1[0][1]} 与 ${times2[0][0]}-${times2[0][1]}`
};
}
}
循环判断每个对象是否有交集
// 判断时间是否有交集
for (let i = 0;i < time.length;i++){
const currentA = time[i];
for (let j = 0;j < time.length;j++){
if(i === j){
continue;
}
const currentB = time[j]
const res = checkTime(currentA.startTime,currentA.endTime,currentB.startTime,currentB.endTime);
if(res.flag){
// 弹出报错
console.log(res.msg);
return;
}
}
}