简单的js 实现24小时时间段不交叉预约功能

78 阅读1分钟
// 重叠:满足 max(A.start, B.start) <= min(A.end, B.end)
// 不重叠:满足 A.end< B.start || A.start > B.end
/**
 * 判断时间段区间是否交叉
 * @param Object isCrossWithOtherProps
 */
export const isCrossWithOther = (props:isCrossWithOtherProps) => (v: any, cb:Function) => {
  const{ required=true, index, form, filed, type } = props
  if (!v?.startTime && !v?.endTime) {
    if (required) {
      return cb(`必填`);
    } else {
      cb(null)
    }
  }
  if(v?.startTime && v?.endTime && filed){
    const filedValues = form?.getFieldValue(filed) as {date?: DateItem}[]
    const startCurrent = time2Minutes(v?.startTime,type)
    const endCurrent = time2Minutes(v?.endTime,type)
    filedValues.forEach((arrItem,idx) => {
    if(arrItem?.date?.startTime && arrItem?.date?.endTime && idx !== index){
      const start = time2Minutes(arrItem?.date?.startTime,type)
      const end = time2Minutes(arrItem?.date?.endTime,type)
      if(Math.max(start, startCurrent) <= Math.min(end, endCurrent)){ // 重叠
        cb(`所选时间段存在冲突,请检查`);
      }
    }
  })
  }
}