Here's an example TypeScript code that calculates the open slots in a calendar given an input of weekday times, blocked slots (with absolute times), and a time range:
typescript
// Define the types for the input data
type WeekdayTime = {
day: number; // 0 for Sunday, 1 for Monday, etc.
start: number; // 24-hour time in minutes, e.g. 9:00 AM is 540
end: number; // 24-hour time in minutes, e.g. 5:00 PM is 720
};
type BlockedSlot = [number, number]; // [start time in minutes, end time in minutes]
type TimeRange = [number, number]; // [start time in minutes, end time in minutes]
// Function to calculate open slots
function calculateOpenSlots(
weekdayTimes: WeekdayTime[],
blockedSlots: BlockedSlot[],
timeRange: TimeRange
): number[][] {
// Convert weekday times to blocked slots
const weekdayBlockedSlots: BlockedSlot[][] = weekdayTimes.map((wt) => {
const [start, end] = [wt.start, wt.end].map((time) => time * 60); // Convert to seconds
const slots = [];
for (let i = start; i < end; i += 30 * 60) { // Add 30-minute slots
slots.push([i, i + 30 * 60]);
}
return slots.map(([start, end]) => [start / 60, end / 60]); // Convert back to minutes
});
// Flatten the weekday blocked slots array
const allBlockedSlots = weekdayBlockedSlots.flat();
// Add the input blocked slots to the array
allBlockedSlots.push(...blockedSlots);
// Sort the blocked slots by start time
allBlockedSlots.sort((a, b) => a[0] - b[0]);
// Initialize the open slots array
const openSlots: number[][] = [];
// Initialize the current start time
let currentStart = timeRange[0];
// Iterate through the blocked slots
for (const [start, end] of allBlockedSlots) {
// If the current start time is before the start of the current blocked slot
if (currentStart < start) {
// Calculate the end time of the open slot
const currentEnd = Math.min(end, timeRange[1]);
// If the open slot is within the time range and is at least 30 minutes long
if (currentEnd > currentStart && currentEnd - currentStart >= 30) {
// Add the open slot to the array
openSlots.push([currentStart, currentEnd]);
}
// Update the current start time to the end of the current blocked slot
currentStart = end;
}
// If the current start time is within the current blocked slot
if (currentStart >= start && currentStart < end) {
// Update the current start time to the end of the current blocked slot
currentStart = end;
}
}
// If the current start time is after the last blocked slot and within the time range
if (currentStart <= timeRange[1] && timeRange[1] - currentStart >= 30) {
// Add the final open slot to the array
openSlots.push([currentStart, timeRange[1]]);
}
// Return the open slots array
return openSlots;
}
// Example usage
const weekdayTimes: WeekdayTime[] = [
{ day: 1, start: 9, end: 17 },
{ day: 3, start: 10, end: 16 },
];
const blockedSlots: BlockedSlot[] = [
[540, 630], // 9:00 AM - 10:30 AM on Monday
[1200, 1230], // 12:00 PM - 12:30 PM on Wednesday
];