JS:检查时间是否不超过间隔数组允许的最大值

JS: check if time doesn't exceed the maximum allowed from an array of intervals

目标是检查所选日期是否不超过最长时间。

我有一组时间间隔。最长时间为 toMinutes - 20 minutes.

您可以在下面找到我的解决方案,它总是 returns false

如何编辑它以匹配下面也指定的预期结果?

const dateRanges = [{fromMinutes: 360, toMinutes: 600}, {fromMinutes: 700, toMinutes: 900}];
// "06:00 - 10:00", "11:40" - "15:00"

const minutesToHourFormat = (minutes) => {
  return new Date(minutes * 1000).toISOString().slice(14, 19);
};

const isWithinMinDate = () => {
  const selectedDate = "14:30";
  
  return dateRanges.every(({ toMinutes }) => {
     const minTime = minutesToHourFormat(toMinutes - 20);
      
     return selectedDate <= minTime;
  })
}

// Expected Result
// 14:30 -> true
// 14:40 -> false
// 14:10 -> true
// 9:50 -> false
// 9:30 -> true

console.log(isWithinMinDate(), 'res')

您的 every 调用应针对这两个限制进行验证,因为给定时间可能在 任何 间隔之外,或者当它在一个结束间隔的 20 分钟内时,在稍后的时间间隔检查时仍会考虑它!

而且我更愿意将选定的时间字符串转换为分钟,而不是相反:

const hourFormatToMinutes = (fmt) =>
    fmt.split(":").reduce((h, m) => h * 60 + +m);

const minutesToHourFormat = (minutes) => 
    new Date(minutes * 1000).toISOString().slice(14, 19);

const dateRanges = [
    { fromMinutes: hourFormatToMinutes("6:00"), toMinutes: hourFormatToMinutes("10:00") }, 
    { fromMinutes: hourFormatToMinutes("11:40"), toMinutes: hourFormatToMinutes("15:00") }
];

const isWithinMinDate = (hourFmt) => {
    const minutes = hourFormatToMinutes(hourFmt);
    return dateRanges.some(({ fromMinutes, toMinutes }) =>
        minutes >= fromMinutes && minutes < toMinutes - 20
    );
}

for (const test of ["14:30", "14:40", "14:10", "9:50", "9:30"]) {
    console.log(test, isWithinMinDate(test));
}