如何过滤daterange数组?

时间:2018-06-26 15:37:07

标签: javascript

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

应用程序应获取一个具有所有可用时间(selectableTimes减去bookedTime)的新数组,并注意时间范围(开始-结束)

如果某人有类似的经历,我会发现我对应该朝哪个方向前进的任何想法表示赞赏。谢谢

// 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"
]

1 个答案:

答案 0 :(得分: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);