Last active
September 10, 2022 11:06
-
-
Save tomasfrancisco/e276bfb3174fca8449c2a55f0971cc2c to your computer and use it in GitHub Desktop.
openingHoursTable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface OpeningHours { | |
/** | |
* weekday from 0 to 6 | |
* 0 - Monday, 6 - Sunday | |
*/ | |
weekDay: number; | |
/** | |
* HH:mm format | |
*/ | |
timeFrom: string; | |
/** | |
* HH:mm format | |
*/ | |
timeTo: string; | |
} | |
interface OpeningHoursInterval { | |
from: string; | |
to: string; | |
} | |
interface OpeningHoursTableRow { | |
weekDay: number; | |
intervals: OpeningHoursInterval[]; | |
} | |
/** | |
* it creates an opening hours table with sorted intervals, suitable for a UI | |
*/ | |
export const getOpeningHoursTable = ( | |
openingHours: OpeningHours[] | |
): OpeningHoursTableRow[] => | |
// Merge all intervals per weekDay | |
openingHours | |
.reduce<OpeningHoursTableRow[]>( | |
(accumulator, openingHours) => { | |
const weekDayIndex = accumulator.findIndex( | |
({ weekDay }) => weekDay === openingHours.weekDay | |
); | |
return [ | |
...accumulator.slice(0, weekDayIndex), | |
{ | |
...accumulator[weekDayIndex], | |
intervals: [ | |
...accumulator[weekDayIndex].intervals, | |
{ from: openingHours.timeFrom, to: openingHours.timeTo }, | |
], | |
}, | |
...accumulator.slice(weekDayIndex + 1), | |
]; | |
}, | |
[ | |
{ weekDay: 0, intervals: [] }, | |
{ weekDay: 1, intervals: [] }, | |
{ weekDay: 2, intervals: [] }, | |
{ weekDay: 3, intervals: [] }, | |
{ weekDay: 4, intervals: [] }, | |
{ weekDay: 5, intervals: [] }, | |
{ weekDay: 6, intervals: [] }, | |
] | |
// Sort all intervals | |
) | |
.map((openingHours) => ({ | |
...openingHours, | |
intervals: openingHours.intervals.sort((openingHoursA, openingHoursB) => { | |
if (openingHoursA.to < openingHoursB.from) { | |
return -1; | |
} | |
if (openingHoursA.to > openingHoursB.from) { | |
return 1; | |
} | |
return 0; | |
}), | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment