Skip to content

Instantly share code, notes, and snippets.

@Koushith
Last active April 14, 2023 08:38
Show Gist options
  • Select an option

  • Save Koushith/a51e67446e9eab6bcd0a6dd91fb4db24 to your computer and use it in GitHub Desktop.

Select an option

Save Koushith/a51e67446e9eab6bcd0a6dd91fb4db24 to your computer and use it in GitHub Desktop.
// Define the initial state of bikes
const bikes = Array(10).fill(true); // true indicates bike is available
// Function to check bike availability for a given time slot
function checkAvailability(startHour, endHour) {
for (let i = startHour; i < endHour; i++) {
if (!bikes[i]) {
return false; // Bike is already booked for the selected time slot
}
}
return true; // All bikes are available for the selected time slot
}
// Function to book a bike for a given time slot
function bookBike(startHour, endHour) {
if (startHour < 0 || endHour < 0 || startHour >= bikes.length || endHour > bikes.length || startHour >= endHour) {
throw new Error('Invalid time slot'); // Validate time slot input
}
if (checkAvailability(startHour, endHour)) {
for (let i = startHour; i < endHour; i++) {
bikes[i] = false; // Mark the bike as booked for the selected time slot
}
return true; // Booking successful
} else {
return false; // Booking failed, as bike(s) are already booked for the selected time slot
}
}
// Example usage:
const startHour = 1; // Booking start hour (e.g., 1 PM)
const endHour = 3; // Booking end hour (e.g., 3 PM)
try {
if (bookBike(startHour, endHour)) {
console.log(`Bike booked from ${startHour}:00 to ${endHour}:00`);
} else {
console.log(`Bike(s) not available for ${startHour}:00 to ${endHour}:00`);
}
} catch (error) {
console.error(error.message); // Log and handle any errors
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment