I want to find out how many days there are between two given days of the week.
This looks to be a case for a well executed slice method; but I just can't get my head around it.
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'
console.log(`${remaining} Days until the next dispatch`)
Monday to Thursday is easy enough :
let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1
But Thursday to Monday (for example) needs some logic that I can't figure out.
You can drop the slice and the if and make use of some modulo arithmetics.
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
function getDays(start, end) {
return (days.indexOf(end) + days.length - days.indexOf(start)) % days.length + 1;
}
console.log(getDays("Monday", "Thursday")); // 4
console.log(getDays("Thursday", "Monday")); // 5
If you decide you want Monday to Thursday to just be 3 instead of 4 (which might be more natural depending on the context) just drop the +1 from the end.
I think you can directly subtract two .indexOf()
values without calling .slice()
, no? Like this:
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
let today = 'Thursday'
let dispatch = 'Monday'
let remaining = days.indexOf(dispatch) - days.indexOf(today) + 1
if (remaining < 1) {
remaining += days.length
}
console.log(`${remaining} Days until the next dispatch`)
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