Kwe*_*eku 6 javascript react-native
我无法自动计算在不同日期开放的不同在线商店的工作日。这里的困难是一些商店在周末营业。我意识到 JavaScript 从星期日0开始计算一周中的天数。
example
store A, WORKING_DAYS = Tue - Sun
store B, WORKING_DAYS = Mon - Fri
store C, WORKING_DAYS = Mon - Tue
store D, WORKING_DAYS = Fri - Mon
Run Code Online (Sandbox Code Playgroud)
// 0 (sunday) - 6 (saturday) give day is thursay which is 4
// workdays fri - tues, ie 5 - 2 but current day is saturday and we
looking at positive values
if( dayStart < currentDay < dayEnd){
return(
<Text style={[styles.h4,styles.tag, {backgroundColor:'#4eae5c'}]}>open</Text>
)
}
if(currentDay) {
return(
<Text style={[styles.h4,styles.tag,
{backgroundColor:'red'}]}>closed</Text>
)
}
Run Code Online (Sandbox Code Playgroud)
因为星期天从 JavaScript 日期返回0,你如何找到星期五和星期一之间的间隔
您声明您想要确定在线商店在特定工作日是否营业,前提是您知道该商店在哪个工作日开门营业以及在哪个工作日关门。天数从 0(星期日)到 6(星期六)。当商店在周五 (5) 开门并在周一 (1) 关门时,这就变得具有挑战性。
otw 的答案中给出了一种简单的解决方案:
if(dayStart is less than dayEnd) {
check whether currentDay >= dayStart and currentDay <= dayEnd
} else {
check whether currentDay <= dayStart or currentDay >= dayEnd
}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是将工作日视为以7 为模的整数环。然后,我们可以使用模运算来检查数字n是否在区间 [ a , b ] 中,并且满足以下不等式,即使a大于b:
( n - a ) mod 7 <= ( b - a ) mod 7
为了解决您的具体问题,我们可以定义一个isOpen()这样的函数:
if(dayStart is less than dayEnd) {
check whether currentDay >= dayStart and currentDay <= dayEnd
} else {
check whether currentDay <= dayStart or currentDay >= dayEnd
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在代码中调用此函数,如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |