首页 > 解决方案 > 生成可用时隙的反应函数不会生成正确的时隙

问题描述

嗨,我想做一个生成可用时隙的函数。它应该生成时间段,同时记住时间段不能与已经进行的约会重叠。在生成时间段之前,用户可以指定要安排哪种约会。每个约会类别都有一个持续时间。所以它还应该检查添加持续时间的时隙是否不重叠。

到目前为止,我一直在努力使这一切正常工作,但它似乎只检查已经预约的开始时间。我在这里有点绕圈子,很想得到一些建议或部分解决方案,我可以实施以使我的想法发挥作用

const GenerateAvailableTimeSlots = (start, serviceObject, allAppointments) => {

  const moment = extendMoment(Moment);

  var x = {
    nextSlot: 15,
    appointmentsOfThatDay: [],
    startTime: '8:00',
    endTime: '20:00'
  };
  // function to filter only the appointment that occur on specified day --> ( start )
  let filterAppointments = (allAppointments, start) => {
    let results = [];
    let filterAppoinments = allAppointments.filter(appoinment => appoinment.date === start.format('MMMM Do YYYY'));
    filterAppoinments.map(appoinment => results.push([appoinment.start.format('HH:mm'), appoinment.end.format('HH:mm')]))
    console.log("results", results);
    return results;
  };

  x.appointmentsOfThatDay = filterAppointments(allAppointments, start)
  console.log("appointmentsOfThatDay", x.appointmentsOfThatDay)

  var slotTime = moment(x.startTime, "HH:mm");
  var endTime = moment(x.endTime, "HH:mm");

  // function to check time slot overlaps with already made appointments 
  function OverlapsScheduledAppointment(slotTime, appointments) {

    //added duration to timeslot so I could check if a suggested timeslot + the duration also doesn't overlap with already made appointment
    var slotTimeWithDuration = slotTime.clone().add(serviceObject.hours, 'hours').add(serviceObject.minutes, 'minutes');

    // I don't know where I also could check for slotTimeWithDuration overlap
    return appointments.some((br) => {
      console.log(slotTime >= moment(br[0], "HH:mm") && slotTime < moment(br[1], "HH:mm"));
      return (slotTime >= moment(br[0], "HH:mm") && slotTime < moment(br[1], "HH:mm"));
    });
  }

  let times = [];
  while (slotTime < endTime) {
    if (!OverlapsScheduledAppointment(slotTime, x.appointmentsOfThatDay)) {
      times.push(slotTime.format("HH:mm"));
    }
    slotTime = slotTime.add(x.nextSlot, 'minutes');
  }

  return times;
};

标签: reactjsfunctionrangemomentjstimeslots

解决方案


我找到了我的问题的答案。我用上面的代码朝着正确的方向前进,但是为了生成可用的时间段,记住你想要安排的服务的持续时间和已经安排的约会。

我不得不更改这行代码:

// 此行仅推送特定日期的过滤约会

filterAppoinments.map(appoinment => results.push([appoinment.start.format('HH:mm'), appoinment.end.format('HH:mm')]))

对此

// 此行过滤特定日期的约会,并将服务的持续时间添加到已安排的约会的开始时间。这样,当我检查为服务生成的时间段是否会与已安排的约会重叠时,它会过滤掉那些将重叠的时间段

filterAppoinments.map(appoinment => results.push([appoinment.start.clone().subtract(serviceObject.hours, 'hours').subtract(serviceObject.minutes, 'minutes').format('HH:mm'), appoinment.end.format('HH:mm')]))


推荐阅读