Created
June 8, 2022 22:27
-
-
Save Frosty21/f2bf3f0fedc5b7f28ca1d848a590b4eb to your computer and use it in GitHub Desktop.
TimeSlot-Grouping.ts
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
import { fromUnixTime, format, getHours } from "date-fns"; | |
import { fromUnixTime, format, getHours } from "date-fns"; | |
const timeSlots = [ | |
{ startTime: 1653998400, endTime: 1654002000 }, //6-31-2022 8am to 6-31-2022 9am | |
{ startTime: 1654002000, endTime: 1654005600 }, //6-31-2022 9am to 6-31-2022 10am | |
{ startTime: 1654012800, endTime: 1654016400 }, //6-31-2022 12pm to 6-31-2022 1pm | |
{ startTime: 1654084864, endTime: 1654088464 }, //2022-06-01 8am to 2022-06-01 9am | |
{ startTime: 1654092064, endTime: 1654095664 }, // 2022-06-01 10am to 2022-06-01 11am | |
{ startTime: 1654106464, endTime: 1654110064 }, // 2022-06-01 2pm to 2022-06-01 3pm | |
]; | |
const consolodateSlots = timeslots.reduce((acc, next) => { | |
const startTime = fromUnixTime(next.startTime); | |
const formattedDate = format(startTime, "PPPP"); | |
const startHour = getHours(startTime); | |
//check if we already have an object in our map from this day | |
if (acc.has(formattedDate)) { | |
const slots = acc.get(formattedDate); | |
const overlappingSlot = slots.findIndex( | |
(slot: { endTime: number }) => getHours(fromUnixTime(slot.endTime)) === startHour, | |
); | |
//if the start time of this slot matches the endtime of an existing slot lets group them | |
if (overlappingSlot >= 0) { | |
slots[overlappingSlot] = { | |
startTime: slots[overlappingSlot].startTime, | |
endTime: next.endTime, | |
}; | |
acc.set(formattedDate, slots); | |
} else { | |
slots.push(next); | |
acc.set(formattedDate, slots); | |
} | |
} else { | |
//add a new key to your map for this day | |
acc.set(formattedDate, [next]); | |
} | |
//return our accumulator so we have the most recent value in the next run | |
return acc; | |
}, new Map()); | |
const timeSlots = Array.from(consolodateSlots).map((slots) => { | |
return ( | |
<> | |
<Typography key={`bookingTime-${slots[0]}`} variant={"body1"}> | |
{slots[0]} | |
</Typography> | |
{slots[1].map((slot: { startTime: number | Date; endTime: number | Date }) => { | |
return ( | |
<> | |
<Typography key={`bookingTime-${slot.startTime}`} variant={"body1"}> | |
{formatDate(slot.startTime, "hh:mm a")} - {formatDate(slot.endTime, "hh:mm a")} | |
</Typography> | |
</> | |
); | |
})} | |
</> | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment