有没有办法进一步优化这个JavaScript(比较当前时间与开放时间)?

时间:2015-11-20 14:58:26

标签: javascript

我正在设置一些JavaScript来比较当前时间与场地的开放和关闭时间(每天可能不同,因此每天的变量不同)。

这是我到目前为止所拥有的:

// Compare current time to today's hours
if (day === 1 && time > monOpen && time < monClose) {
    venueIsOpen();
} else if (day === 2 && time > tuesOpen && time < tuesClose) {
    venueIsOpen();
} else if (day === 3 && time > wedOpen && time < wedClose) {
    venueIsOpen();
} else if (day === 4 && time > thursOpen && time < thursClose) {
    venueIsOpen();
} else if (day === 5 && time > friOpen && time < friClose) {
    venueIsOpen();
} else if (day === 6 && time > satOpen && time < satClose) {
    venueIsOpen();
} else if (day === 0 && time > sunOpen && time < sunClose) {
    venueIsOpen();
} else {
    venueIsClosed();
}

显然非常简单 - 有没有办法优化这个?

2 个答案:

答案 0 :(得分:2)

首先,我们可以合并这些background-color:transparent语句的负载:

if

那仍然很难看,对吧?但那里有一些逻辑......我们可以在开/关时使用数组:

// Compare current time to today's hours
if (day === 1 && time > monOpen && time < monClose ||
    day === 2 && time > tuesOpen && time < tuesClose ||
    day === 3 && time > wedOpen && time < wedClose ||
    day === 4 && time > thursOpen && time < thursClose ||
    day === 5 && time > friOpen && time < friClose ||
    day === 6 && time > satOpen && time < satClose ||
    day === 0 && time > sunOpen && time < sunClose) {
        venueIsOpen();
} else {
    venueIsClosed();
}

或者,使用ternary condition时更短:

var open = [sunOpen, monOpen, tuesOpen, wedOpen, thursOpen, friOpen, satOpen],
    close = [sunClose, monClose, tuesClose, wedClose, thursClose, friClose, satClose];

if(time > open[day] && time < close[day])
    venueIsOpen();
else
    venueIsClosed();

答案 1 :(得分:0)

以下是另一种可以缩短代码的方法:

// These are the 7 days of the week
var openings = [
{opening: 1,close: 2},
{opening: 2,close: 4},
{opening: 5,close: 7},
{opening: 1,close: 5},
{opening: 1,close: 3},
{opening: 2,close: 9},
{opening: 1,close: 2}
];

// loop through all of them
for(var i=0, l=openings.length; i<l; i++) {
    // if the current time is bigger than the current day opening time and smaller than the current closing time call venueIsOpen(), otherwise call venueIsClosed()
    (openings[day].opening < time && openings[day].close > time) ? venueIsOpen() : venueIsClosed();   
}