JS array of time slots based on opening hours

254 Views Asked by At

I am writing an order ahead application that allows the user to select a pick up time from a select box.

This pickup time must be in intervals of x number of minutes i.e. every 20 minutes.

It needs to take into account business opening hours i.e. 12:00 > 14:00 and 16:30 > 21:30 i.e. only generate time slots between these hours, lunchtime opening and evening opening.

I am using data-fns and have the basic functionality working i.e. start time and hardcoded end time, it generates an array of available time slots at the minute interval.

import { addMinutes, set } from "date-fns";

const generateAvailableTimeSlots = (slotSizeInMinutes: number) => {
  const now = new Date();
  let firstAvailableSlot = now;

  while (firstAvailableSlot <= now) {
    // Set the first available slot to now + slotSizeInMinutes e.g. now + 20 minutes
    firstAvailableSlot = addMinutes(now, slotSizeInMinutes);
  }

  // Currently hard coded end time i.e. end of business day
  const endTime = set(now, { hours: 23, minutes: 30 });

  let slot = firstAvailableSlot;
  let availableTimeSlots = [];
  while (slot < endTime) {
    availableTimeSlots.push(slot);
    slot = addMinutes(slot, slotSizeInMinutes);
  }

  return availableTimeSlots;
};

export default generateAvailableTimeSlots;

What would be the best way to improve this and to take into account business opening hours? i.e. Sunday the business is not open in the morning, every other day it's open for 2 hours over lunch and then again in the evening.

I guess keeping it simple I could pass in a start time and an end time and call the function twice to generate two arrays of time slots (for lunchtimes and evenings) however it would be convenient only to call the function once and just not have the closed time slots selectable i.e. maybe return an array of objects for all available slots but mark some as not available

0

There are 0 best solutions below