You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现数组中无时间(含起止日期)重叠的预约存储

完整的无重叠预约校验与实现方案

针对需求,我们需要在原有时间校验基础上补充日期区间重叠判断,整合两者实现完整的预约冲突校验逻辑,具体实现如下:

1. 核心判断逻辑

日期区间重叠判断

两个日期区间[newStart, newEnd]和[exStart, exEnd]重叠的条件为:不满足「新区间完全在旧区间之前」或「新区间完全在旧区间之后」,对应代码:

function isDateRangeOverlapping(newRange, existingRange) {
  // 反向判断:无重叠则返回false,重叠则返回true
  return !(newRange.endDay < existingRange.startDay || newRange.startDay > existingRange.endDay);
}

时间区间重叠判断(优化版)

合并所有时间重叠场景(包含、被包含、部分重叠)的判断逻辑:

function isTimeRangeOverlapping(newTime, existingTime) {
  const { startTime: ns, endTime: ne } = newTime;
  const { startTime: es, endTime: ee } = existingTime;
  // 覆盖四种重叠情况:新时间起止点在旧时间内、新时间完全覆盖旧时间
  return (ns >= es && ns <= ee) || (ne >= es && ne <= ee) || (ns <= es && ne >= ee);
}

2. 完整预约校验函数

遍历所有已有预约,先判断日期区间是否重叠,若重叠则进一步校验时间区间:

function isNewAppointmentValid(newAppointment, allAppointments) {
  const { startDay: newStart, endDay: newEnd, "Booked Appointments": newTimes } = newAppointment;

  for (const existing of allAppointments) {
    const { startDay: exStart, endDay: exEnd, "Booked Appointments": exTimes } = existing;

    // 日期区间无重叠,直接跳过时间校验
    if (!isDateRangeOverlapping({ startDay: newStart, endDay: newEnd }, { startDay: exStart, endDay: exEnd })) {
      continue;
    }

    // 日期重叠,逐个校验时间区间
    for (const newTime of newTimes) {
      for (const exTime of exTimes) {
        if (isTimeRangeOverlapping(newTime, exTime)) {
          return false; // 存在冲突,返回无效
        }
      }
    }
  }
  return true; // 无冲突,返回有效
}

3. 预约添加函数

校验通过后将新预约加入数组,返回操作结果:

function addAppointment(newAppointment, allAppointments) {
  if (isNewAppointmentValid(newAppointment, allAppointments)) {
    allAppointments.push(newAppointment);
    return { success: true, message: "预约添加成功" };
  }
  return { success: false, message: "新预约与已有预约时间重叠,无法添加" };
}

4. 测试示例

// 初始预约列表
let Allappointments = [
  {
    "startDay": 0,
    "endDay": 7,
    "Booked Appointments": [
      { "startTime": 1530, "endTime": 1700 },
      { "startTime": 1030, "endTime": 1300 }
    ]
  }
];

// 测试1:添加无冲突预约(周一至周三,14:00-15:00)
const validAppt = {
  startDay: 1,
  endDay: 3,
  "Booked Appointments": [{ startTime: 1400, endTime: 1500 }]
};
console.log(addAppointment(validAppt, Allappointments));
// 输出:{ success: true, message: "预约添加成功" }

// 测试2:添加冲突预约(周二至周四,15:00-16:00,与已有1530-1700重叠)
const invalidAppt = {
  startDay: 2,
  endDay: 4,
  "Booked Appointments": [{ startTime: 1500, endTime: 1600 }]
};
console.log(addAppointment(invalidAppt, Allappointments));
// 输出:{ success: false, message: "新预约与已有预约时间重叠,无法添加" }

边界说明

  • 若允许预约时间首尾衔接(如已有预约17:00结束,新预约17:00开始),可将时间重叠判断中的>=改为>、<=改为<
  • 日期范围为闭区间(包含startDay和endDay),若需改为开区间,可调整日期重叠判断的条件

内容的提问来源于stack exchange,提问作者Ahsan Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:15:07