I want to check with Javascript if a week number (with year) is within two other week numbers.
Example data: Year-Week
startDate: 2020-32
endDate: 2021-52
checkDate: 2021-30
.
In this case checkDate is within the two years.
How do I make Javascript know this too? I figured I should check if the date is bigger than startDate and smaller than endDate. But doing these checks on both years and weeks seems to get quite big. Here is what I have implemented:
/**
* Returns whether the week is within the two given weeks or not.
*
* @param {Number} startYear Example data: 2020
* @param {Number} startWeek 32
* @param {Number} endYear 2021
* @param {Number} endWeek 52
* @param {Number} checkYear 2021
* @param {Number} checkWeek 30
* @returns true or false
*/
function isWeekWithinTwoWeeks(startYear, startWeek, endYear, endWeek, checkYear, checkWeek) {
// If checkYear is same as startyear and checkWeek bigger or equal to startWeek and checkWeek smaller or equal than endWeek, its not allowed.
// Else if checkYear is bigger than startYear, and checkYear is smaller than endYear it means it is in between.
// Also if checkYear is bigger than startYear but checkYear is not smaller but equal to endYear, and checkWeek is smaller or equal to endWeek, it is in between.
if (checkYear === startYear) {
if (checkWeek >= startWeek) {
if (checkWeek <= endWeek) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
}
}
} else if (checkYear > startYear) {
if (checkYear < endYear) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
} else if (checkYear === endYear) {
if (checkWeek <= endWeek) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
}
}
}
return true;
}
I think it could be done in a much simpler way and would like to know if there is much to improve here and how. I do know I could use &&
signs in the if statements to make them more of a one-liner, but thought this might be more readable.