I want to return true if a week is between two weeks. I.e., the period is week 48 (2021) to week 3 (2022). I then want to return true if a week is in between.
Lesson week and year is what I'm checking is inbetween. Start week & year and end week & year is the period.
My code below doesn't work for the example (week 48 2021 -> week 3 2022)
I'd rather not convert to Date objects but if it's needed I will.
const isSamePeriod = (
lessonWeek,
lessonYear,
startWeek,
startYear,
endWeek,
endYear
) => {
if (lessonWeek >= startWeek && lessonYear === startYear) {
if (lessonWeek <= endWeek && lessonYear === endYear) {
return true;
}
}
return false;
};
CodePudding user response:
You can concatenate the values as strings of year week provided the week is zero padded, then compare, e.g.
const isSamePeriod = (
lessonWeek,
lessonYear,
startWeek,
startYear,
endWeek,
endYear
) => {
let z = n => ('0' n).slice(-2);
let lesson = lessonYear z(lessonWeek);
let start = startYear z(startWeek);
let end = endYear z(endWeek);
return lesson >= start && lesson <= end;
};
// Examples
[[47,2021],
[48,2021],
[50,2021],
[ 1,2022],
[ 3,2022],
[ 4,2022]
].forEach(
arr => console.log(arr ' ' isSamePeriod(...arr, 48,2021, 3,2022))
);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
The checks need to be separate, but you have the second one nested inside the first. Also, you only need to check the week if the years match; see comments:
const isSamePeriod = (
lessonWeek,
lessonYear,
startWeek,
startYear,
endWeek,
endYear
) => {
return (
// Year is valid
(lessonYear >= startYear && lessonYear <= endYear) ||
// Lesson is not in the start year or is late enough in the start year
(lessonYear !== startYear || lessonWeek >= startWeek) ||
// Lesson is not in the end year or is early enough in the end year
(lessonYear !== endYear || lessonWeek <= endWeek)
);
};
Or you can take the approach of converting years to weeks:
const isSamePeriod = (
lessonWeek,
lessonYear,
startWeek,
startYear,
endWeek,
endYear
) => {
const lesson = lessonYear * 52 lessonWeek;
const start = startYear * 52 startWeek;
const end = endYear * 52 endWeek;
return lesson >= start && lesson <= end;
};