Skip to content

Instantly share code, notes, and snippets.

@hemakumarm72
Last active April 13, 2025 08:17
Show Gist options
  • Save hemakumarm72/ed4ea9492b630e30bd1936c4d685ab26 to your computer and use it in GitHub Desktop.
Save hemakumarm72/ed4ea9492b630e30bd1936c4d685ab26 to your computer and use it in GitHub Desktop.
type Booking = {
start: string;
end: string;
};
const booking: Booking[] = [
{ start: '2024-05-04T13:00:00.000Z', end: '2024-05-04T14:00:00.000Z' },
{ start: '2024-05-04T15:00:00.000Z', end: '2024-05-04T16:00:00.000Z' },
{ start: '2024-05-04T17:00:00.000Z', end: '2024-05-04T18:00:00.000Z' },
];
function availableSlot(booking: Booking[], interval: number, gap: number) {
booking.sort(
(a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()
);
let startTime = '2024-05-04T00:00:00.000Z',
endTime = booking[0].start;
const available = [] as Booking[];
for (let item = 0; item <= booking.length; item++) {
const currentBooking = booking[item];
const gapResult = gapTime(startTime, endTime, interval, gap);
available.push(...gapResult);
startTime = currentBooking?.end ?? booking[item - 1];
endTime = booking[item + 1]?.start ?? '2024-05-04T23:00:00.000Z';
}
return available;
}
function gapTime(
startTime: string,
endTime: string,
interval: number,
gap: number
): Booking[] {
const result = [] as Booking[];
let start = new Date(startTime);
let end = new Date(endTime);
while (start < end) {
//console.log(next);
let next = new Date(start.getTime() + interval * 60 * 60 * 1000);
if (next <= end) {
result.push({
start: new Date(start.getTime() + gap * 60 * 1000).toISOString(),
end: new Date(next.getTime() - gap * 60 * 1000).toISOString(),
});
}
start = next;
}
return result;
}
const slot = availableSlot(booking, 1, 10);
console.log(slot);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment