Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/wojtekmaj/opening-hours-utils. A collection of opening hours-related utilities.
Something went wrong. Try again.
1.6 kB · 53 lines
TypeScript
at benchmarks
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import { WEEKDAY_NAMES } from './constants.js';
import type { DayGroups, Hour, HourGroups, Weekday, WeekdayName, ZeroToSix } from './types.js';
export function getDayDiff(from: Weekday, to: Weekday): ZeroToSix { return ((7 + (to - from)) % 7) as ZeroToSix;}
export function getHourGroups(dayGroups: DayGroups): HourGroups { return dayGroups.reduce<HourGroups>((acc, dayGroup) => { return acc.concat(dayGroup.hours); }, []);}
export function getMinutesFromMidnightFromDate(date: Date): number { return date.getHours() * 60 + date.getMinutes();}
export function getMinutesFromMidnightFromString(hour: Hour): number { const [hours, minutes] = hour.split(':');
return Number(hours) * 60 + Number(minutes);}
const weekdayNamesEntries = Object.entries(WEEKDAY_NAMES);
export function getWeekday(weekdayName: WeekdayName): Weekday { const weekdayNamesEntry = weekdayNamesEntries.find(([, value]) => value === weekdayName);
if (!weekdayNamesEntry) { throw new Error(`Invalid weekday name: ${weekdayName}`); }
return Number(weekdayNamesEntry[0]) as Weekday;}
export function getWeekdayName(weekday: Weekday): WeekdayName { return WEEKDAY_NAMES[weekday];}
export function isValidHour(hour: unknown): hour is Hour { if (!hour || typeof hour !== 'string') { return false; }
return hour.match(/^(0?[0-9]|[123][0-9]|4[0-8]):[0-5][0-9]$/) !== null;}
const weekdayNamesValues = Object.values(WEEKDAY_NAMES);
export function isValidWeekdayName(weekday: unknown): weekday is WeekdayName { return weekdayNamesValues.includes(weekday as WeekdayName);}