Javascript gets days from a range of week ranges, between two numbers corresponding to ISOWeekday
So I am trying to get an array of day numbers in a specific range corresponding to
ISOWeekday
(returns 1-7, where 1 is Monday and 7 is Sunday)
So, if the work week starts on Sunday ( 7
) and ends on Tuesday ( 4
),
I need to output this array:
7,1,2,3,4
const startWeek = 7;
const endWeek = 4;
for (let i = 1; i < 7; i++) {
if (i > startWeek && i < endWeek) {
console.log(i);
}
}
source to share
You can use modulo operations, for example:
const startWeek = 7;
const endWeek = 4;
for (let i = 0; i <= (endWeek + 7 - startWeek) % 7; i++) {
let week = (startWeek + i - 1) % 7 + 1;
console.log(week);
}
Written in a functional way using a callback function argument Array.from
:
const startWeek = 7;
const endWeek = 4;
var weeks = Array.from(Array((endWeek + 7 - startWeek) % 7 + 1),
(_,i) => (startWeek + i - 1) % 7 + 1);
console.log(weeks);
source to share
You can use bitwise operations to give a range of top cap numbers.
For example, for a loop from 5 to 3:
5 & 7 == 5
6 & 7 == 6
7 & 7 == 7
8 & 7 == 0
9 & 7 == 1
10 & 7 == 2
11 & 7 == 3
However, you don't want 8 to give you 7; you want it to give you 1. So try the module:
5 % 7 == 5
6 % 7 == 6
7 % 7 == 0
8 % 7 == 1
9 % 7 == 2
10 % 7 == 3
11 % 7 == 4
But this way makes 7 give you 0!
So you can index the zero format (make it 0-6, not 1-7) and use one of the methods above
Or you can add corner cases to your code:
if (x == 8)
x++;
For the module:
if (x == 7)
x++;
source to share