Context:
I'm storing the day of the week the user made the last purchase on my website. The function getDay() returns a number corresponding to that weeks day, beeing 0 as Sunday and 6 as Saturday. So a purchase made today, 07/14/2022, will store the number 4, Thursday.
Problem: Knowing the date and day of the week the user made the purchase, i want it to know, base on the todays date, how many days will take to reach the weeks day, which the user made that purchase!
Clarifying:
Exemple - If a user made a purchase on day of the week 0, sunday, based on todays date, 07/14/2022, so number 4, how many days will take to reach day 0? Adding number by number, we know will take 3 days, but how can i calculate dynamically???
More Examples:
Find how many days will take to reach day 3, todays beeing day 4. So we need to go through day 5,6,0,1,2, so 5
Find how many days will take to reach day 2, todays beeing day 6. So we need to go through day 0, 1 and 2, so 3
You could take a delta of to and from day plus seven and takes the remainder by seven.
const
getDays = (from, to) => (7 + to - from) % 7;
console.log(getDays(0, 0)); // 0
console.log(getDays(6, 0)); // 1
console.log(getDays(4, 3)); // 5 6 0 1 2 3 -> 6
console.log(getDays(6, 2)); // 0 1 2 -> 3
.as-console-wrapper { max-height: 100% !important; top: 0; }