Как оптимизировать данный код Javasript?

написал код, работает все хорошо, но мне кажется можно было бы куда лучше оптимизировать.

const [working, setWorking] = useState(true)
  const workTime = () => {
    const simpleNotWorking = [6, 7]
    const weekendNotWorking = [6, 7, 8, 9, 10]
    const currentDate = new Date()
    const currentTime = currentDate.getHours()
    const currentDay = currentDate.getDay()

    if (currentDay >= 1 && currentDay <= 5) {
      if (simpleNotWorking.includes(currentTime))
        setWorking(false)
    }
    if (currentDay === 6 || currentDay === 7) {
      if (weekendNotWorking.includes(currentTime)) {
        setWorking(false)
      }
    }
  }

Суть в следующем, есть ресторан, в будни дни работает с 8 утра до 6 утра следующего дня( по будням лишь 2 часа не работают с 6 утра до 8 ) По выходным работают с ( 11 утра до 6 утра)

Я сделал 2 массива в котором указал в котором ресторан не работает Так же дни недели получаю через getDay ( 1-7) И прохожусь обычными проверками

Как можно сократить код?


Ответы (2 шт):

Автор решения: Marina Mitasova

единственное, что приходит в голову:

  const [working, setWorking] = useState(true)
  const workTime = () => {
    const notWorking = [[6, 7, 8, 9, 10], [6, 7]]
    const currentDate = new Date()
    const currentTime = currentDate.getHours()
    const currentDay = currentDate.getDay()
    
    if (notWorking[ +(currentDay >= 1 && currentDay <= 5) ].includes(currentTime))
        setWorking(false)
  }

P.S. getDay разве не 0 для воскресенья возвращает?

→ Ссылка
Автор решения: Aziz Umarov

Можно так посмотреть.

 const [working, setWorking] = useState(true)
  const workTime = () => {
    const currentDate = new Date()
    const currentTime = currentDate.getHours()
    const currentDay = currentDate.getDay();
    ([6, 7].includes(currentTime) || ([0,6].includes(currentDay) && [8, 9, 10].includes(currentTime))) && setWorking(false); // смотрим на время [6, 7] закрыто в любой день, а  на выходных смотрим дополнительно на [8, 9, 10] 
  }

→ Ссылка