Create a hotel booking system
by Vasil Svetoslavov
HTML
<div class="container">
<button onclick="initHotel()">Create hotel</button>
<button id="btnBookRoom3" onclick="bookRoom3()" disabled="true">Book room 3</button>
<button id="btnBookRoom" onclick="bookRoom()" disabled="true">Book a room</button>
<div id="roomContainer">
</div>
<div id="log">
</div>
</div>
TypeScript
class Room {
public readonly roomId: number;
private available: boolean;
constructor(roomId) {
this.roomId = roomId;
this.available = true;
}
public isAvailable() {
return this.available;
}
book() {
if (!this.available) {
//return false;
throw new Error("Room " + this.roomId + " is not available at the moment");
}
this.available = false;
console.log("You just booked room " + this.roomId + ". Congratulations!");
}
}
class Hotel {
private name: string;
private numberOfRooms: number;
private rooms: Room[];
constructor(name: string, numberOfRooms: number) {
this.name = name;
this.numberOfRooms = numberOfRooms;
this.rooms = new Array();
for (let roomId = 1; roomId < numberOfRooms; roomId++) {
this.rooms.push(new Room(roomId));
}
}
firstAvailableRoom() {
let room = this.rooms.find((r) => r && r.isAvailable()===true);
if (!room) {
throw new Error("There are no rooms available at the moment!");
}
return room;
}
findById(roomId:number) {
if (!roomId) {
throw new Error("No roomId passed to findById");
}
let room = this.rooms.find((r) => r && r.roomId === roomId);
if (!room) {
throw new Error("Room " + roomId + " not found. Creepy, huh?");
}
return room;
}
findAvailableRoomById(roomId) {
const room = this.findById(roomId);
if (!room.isAvailable()) {
throw new Error("Room " + roomId + " is not available at the moment");
}
return room;
}
findAvailableRoom(roomId) {
if (roomId) {
return this.findAvailableRoomById(roomId);
} else {
return this.firstAvailableRoom();
}
}
book(roomId) {
try {
let room = this.findAvailableRoom(roomId);
room.book();
} catch (err) {
console.error(err.message);
}
}
}
var hotel;
function...