The goal is to check, whether the selected date doesn't exceed the maximum time.
I have an array of time intervals. The maximum time is toMinutes - 20 minutes
.
Below you can find my solution, which always returns false
.
How can it be edited to match expected result, which is also specified below?
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')
CodePudding user response:
Your every
call should verify against both limits, because the given time could be outside any interval, or when it is within 20 minutes for one ending interval, it would be still considered when checking against a later interval!
And I would prefer converting the selected time string to minutes, instead of doing the inverse:
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));
}