Skip to content

Instantly share code, notes, and snippets.

@verdi327
Created September 20, 2019 03:53
Show Gist options
  • Save verdi327/9f3f0c9367b809b5085a6888ba18f061 to your computer and use it in GitHub Desktop.
Save verdi327/9f3f0c9367b809b5085a6888ba18f061 to your computer and use it in GitHub Desktop.
hotel-booking
class Hotel {
constructor(numRooms) {
this.totalRooms = numRooms;
this.reservations = {};
}
book(startDay, endDay) {
let checkIn = this._keyify(startDay);
// do we have any reservations at this date
if (this.reservations[checkIn] && this.reservations[checkIn].length) {
// grab an available room from end of array
const bookedRoom = this.reservations[checkIn].pop();
this._removeRoomFromFutureAvailability(startDay, endDay, bookedRoom);
return `You're booked at room ${bookedRoom}`;
} else if (this.reservations[checkIn] && this.reservations[checkIn].length === 0) {
// the array was empty, no available rooms
return 'Hotel is fully booked on desired check-in day';
} else {
this.reservations[checkIn] = this._setAllRoomsAvailable();
const bookedRoom = this.reservations[checkIn].pop();
this._removeRoomFromFutureAvailability(startDay, endDay, bookedRoom);
return `You're booked at room ${bookedRoom}`;
}
}
_removeRoomFromFutureAvailability(startDay, endDay, bookedRoom) {
// increment by 1 until we reach the end day
// removing the room from availability
const checkIn = this._keyify(startDay);
const checkOut = this._keyify(endDay);
for (let i=checkIn+1; i<=checkOut; i++) {
i = i+''; // small hack: converting from number to string so key can be found
if (this.reservations[i] && this.reservations[i].length) {
// remove the room from availability
this.reservations[i] = this.reservations[i].filter(room => room !== bookedRoom);
} else {
// don't have this key yet, add it, but don't include this room as available
this.reservations[i] = this._setAllRoomsAvailable(bookedRoom);
}
}
}
_setAllRoomsAvailable(blockedRoom=null) {
const availableRooms = [];
for (let i=1; i<=this.totalRooms; i++) {
if (blockedRoom === i) continue;
availableRooms.push(i);
}
return availableRooms;
}
_keyify(strDate) {
const numArray = strDate.split('-').map(strNum => Number(strNum));
return numArray[2] + numArray[0] + numArray[1];
}
}
// create a new hotel with 3 total rooms
const hotel = new Hotel(3);
// make a booking - should be able to book at this date 3 times before you reach capacity
console.log(hotel.book('9-10-2019', '9-12-2019'));
console.log(hotel.book('9-10-2019', '9-12-2019'));
console.log(hotel.book('9-10-2019', '9-12-2019'));
console.log(hotel.book('9-10-2019', '9-12-2019'));
console.log(hotel.book('9-13-2019', '9-14-2019'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment