ARTICLE AD BOX
Context: I am building a booking system for a business (e.g., a barber shop). I need to return an array of all available time slots for a given day or week.
The Setup:
Business hours: 08:00 AM to 06:00 PM.
Service duration: 50 minutes.
I have a PostgreSQL query that successfully returns a list of unavailable (already booked) appointments for a specific worker.
Example of booked appointments from the DB: [05/03-10:00, 05/03-10:50, 05/03-12:00]
Expected Output: I need to return the available slots based on the business hours and the gaps between those booked appointments: [05/03-08:00, 05/03-08:50, 05/03-12:50...]
My Current Approach (and Problem): Right now, my logic tries to iterate through the booked appointments and calculate the available gaps between them.
However, this is turning into a "Frankenstein" of edge cases. For example:
Empty lists: If a day has no appointments, I have to write separate logic to fill the whole day.
Spaced days: If the user searches for a whole week, and the DB only returns appointments for Monday and Thursday, my loop struggles to seamlessly fill in the completely open days in between (Tuesday and Wednesday) because it's only looking at arr[i] and arr[i+1].
My Question: Calculating availability by finding gaps between existing records feels incredibly brittle. Is there a standard algorithm or design pattern for interval scheduling that handles these edge cases (like empty days and overlapping durations) more cleanly?
