So I'm trying to get an array of day numbers, in a specific range, conforming to
ISOWeekday (returns 1-7 where 1 is Monday and 7 is Sunday)
So if a work week starts at Sunday (7) and ends on Thuesday (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);
}
}
You can use modulo operations, like this:
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 the callback function argument of 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);
You can use bitwise operations to give a number range an upper cap.
For example, to loop from 5 around 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 modulus:
5 % 7 == 5
6 % 7 == 6
7 % 7 == 0
8 % 7 == 1
9 % 7 == 2
10 % 7 == 3
11 % 7 == 4
But that way causes 7 to give you a 0!
So, you could zero-index your format (make it 0-6, not 1-7) and use one of the methods above
Or, you could add corner cases in your code like so:
if (x == 8)
x++;
For modulus:
if (x == 7)
x++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With