import { useMemo } from 'react' import { WEEKDAYS } from '../constants.js' import { parseTimeToMinutes } from '../utils/index.js' // Ensure WEEKDAYS is defined in an external constants file type Input = [string, string] export type HumanReadableOpeningHours = { openDay :string; closeDay :string; openTime :string; closeTime:string; } type Options = { format?:12 | 24; } /** * Converts opening and closing hours of the week into a human-readable format, * with an option to format times in 12-hour or 24-hour format. * * @param {Input} input - * Tuple representing opening and closing times in "hours:minutes" format. * @param {Options} options - * Configuration options, including time format. * @returns {HumanReadableOpeningHours} An object with human-readable * opening and closing days and times. */ const useHumanReadableOpeningHours = ( input: Input, options?: Options, ): HumanReadableOpeningHours => useMemo( () => { // Destructure options in the function body with a default value for format const { format = 24 } = options || {} const days = Object.values(WEEKDAYS) const calculateDayAndTime = (totalMinutes: number) => { const dayIndex = Math.floor(totalMinutes / (24 * 60)) % 7 const day = days[dayIndex] let hour = Math.floor((totalMinutes % (24 * 60)) / 60) const minute = (totalMinutes % (24 * 60)) % 60 let suffix = '' if (format === 12) { suffix = hour >= 12 ? ' PM' : ' AM' hour = hour % 12 || 12 // Convert 0 to 12 for 12-hour format } const time = `${hour.toString().padStart( 2, '0', )}:${minute .toString() .padStart( 2, '0', )}${suffix}` return { day, time, } } const [ openMinutes, closeMinutes, ] = input.map(parseTimeToMinutes) const openInfo = calculateDayAndTime(openMinutes) const closeInfo = calculateDayAndTime(closeMinutes) // Adjust closeDay if closing time is the next week const adjustedCloseDay = openMinutes <= closeMinutes ? closeInfo.day : days[(days.indexOf(closeInfo.day) + 1) % 7] return { openDay :openInfo.day, closeDay :adjustedCloseDay, openTime :openInfo.time, closeTime:closeInfo.time, } }, [ input, options, ], ) export default useHumanReadableOpeningHours