How do I calculate the opening days of online stores with different working days.?
You state that you want to determine whether an online store is open on a specific weekday, given that you know which weekday it opens and which weekday it closes. Days are numbered from 0 (Sunday) to 6 (Saturday). This gets challenging when a store opens on Friday (5) and closes on Monday (1).
A straightforward solution is the one given in the answer by otw:
if(dayStart is less than dayEnd) {
check whether currentDay >= dayStart and currentDay <= dayEnd
} else {
check whether currentDay <= dayStart or currentDay >= dayEnd
}
Another solution is to view the weekdays as a ring of integers modulo 7. We can then use modular arithmetic to check whether a number n is in the interval [a, b] with the following inequality, even when a is larger than b:
(n - a) mod 7 <= (b - a) mod 7
To solve your specific problem, we can define an isOpen()
function like this:
function isOpen(currentDay, dayStart, dayEnd){
return mod(currentDay - dayStart, 7) <= mod(dayEnd - dayStart, 7);
}
function mod(a, n){
return (a % n + n) % n; // guarantees positive modulo operation
}
Then, you can call this function in your code like this:
if(isOpen(currentDay, dayStart, dayEnd)) {
return (
<Text style={[styles.h4, styles.tag, {backgroundColor: '#4eae5c'}]}>open</Text>
);
} else {
return (
<Text style={[styles.h4, styles.tag, {backgroundColor: 'red'}]}>closed</Text>
);
}