如何过滤daterange数组?

问题描述 投票:1回答:1

我正在建立日历预订功能,其中业务经理有一定的工作时间,有些时间是预订的。使用应该能够选择插槽以防止超量预订

应该获得一个包含所有可用时间的新数组(selectableTimes减去expectedTime),注意时间段周期(开始 - 结束)

如果有人有类似的经历,我发现有什么想法,我应该看到什么方向。谢谢

// time when you can possibly book a meeting
// aka working time
const selectableTimes = [
  "8:00", "8:30", "9:00", "9:30",
  "10:00", "10:30", "11:00", "11:30",
  "12:00", "12:30", "13:00", "13:30",
  "14:00", "14:30", "15:00", "15:30",
  "16:00", "16:30", "17:00", "17:30",
  "18:00", "18:30", "19:00", "19:30",
  "20:00"
]

// my calendar is booked on (api responce)
const bookedTime = [
  {start: "16:30", end: "17:30"},
  {start: "18:15", end: "19:00"}
]

// build new array with available dates
let availableDates = selectableTimes.filter( x => {
      // check every event in api responce
      bookedTime.map( ev => {
        // I'm stuck :)
        ev.start < x ? true : false
      })
    })

// should get something like
const result = [
  "8:00", "8:30", "9:00", "9:30",
  "10:00", "10:30", "11:00", "11:30",
  "12:00", "12:30", "13:00", "13:30",
  "14:00", "14:30", "15:00", "15:30",
  "16:00",
  "19:00", "19:30",
  "20:00"
]
javascript
1个回答
1
投票

// I generate the hour:minute from 08:00 to 20:30
const selectableTimes = [];

for (let i = 8; i < 20; i += 1) {
  selectableTimes.push(`${i}:00`);
  selectableTimes.push(`${i}:30`);
}

// my calendar is booked on (api responce)
const bookedTime = [{
    start: '16:30',
    end: '17:30',
  },
  {
    start: '18:15',
    end: '19:00',
  },
];

// transform the hour:minute to comparable number
function t(v) {
  const [
    hour,
    min,
  ] = v.split(':');

  return Number(hour) * 60 + Number(min);
}

// filter the values
// The Array.some is used to see if the selectable time is
// inside of a booked period
const filtered = selectableTimes.filter(x =>
  !bookedTime.some(y => t(y.start) <= t(x) && t(y.end) >= t(x)));

console.log(filtered);
© www.soinside.com 2019 - 2024. All rights reserved.