Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 18
Module 7 · Design problems IV: ATMs, chess and hotels · Chapter 18 of 28
Hotel Management: Rooms, Bookings, Stays and Billing
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps, Design Patterns in TypeScript: Creational, Structural and Behavioural and Parking Lot: Floors, Spots, Tickets and Fees. Next up: Online Shopping Store: Catalogue, Cart, Orders and Shipments.
Part 1 · Requirements
What the hotel must do
A hotel sells the same night twice if its booking list and its room list disagree. This chapter builds a small hotel system in which bookings reserve nights by room type, rooms track their own cleanliness and a folio collects the bill.
A requirement is a sentence about the system that someone can check. Functional requirements say what the system does, and we write them before any class exists. Here is our list, for a small hotel in Udaipur with five rooms.
- There are three room types: single, double and suite. The hotel has two singles, two doubles and one suite.
- A guest books a room type for a range of nights, given as a check-in day and a check-out day. The stay covers the nights from the check-in day up to, but not including, the check-out day.
- A booking is refused when some night in the range has no room of that type left.
- A specific room is chosen at check-in, not at booking. It must be vacant and clean.
- A guest can check in on or after the booked day, and before the check-out day.
- During the stay, reception adds charges such as room service to the guest's folio, the running list of what the guest owes.
- At check-out, the folio gets one room charge for each night stayed. The invoice adds a flat tax, and the room becomes vacant but dirty.
- A housekeeper marks a dirty room clean. A guest can cancel before checking in.
Everything here is our model. The rates and the tax are made up for this chapter and are not any hotel's tariff or any tax rule.
A short prompt such as "design a hotel system" leaves rules open, so we ask questions. Ask the ones whose answers change a class or a method.
| Question | If the answer is yes |
|---|
Quality, numbers and scope
Non-functional requirements say how well the system behaves. Three matter here. The hotel must never promise more rooms of a type than it owns on any night. A refused action must change nothing: not a booking, not a room and not a folio. And money must add exactly, so it is an integer number of paise, a hundredth of a rupee, and a ₹3,000 night is 300000. Decimals do not add exactly in floating point, as the parking lot chapter showed.
Dates are plain days such as 2026-12-01, with no times and no time zones. A hotel thinks in calendar days, and removing the clock removes a whole family of bugs.
We rejected two designs. The first gives a booking its room number at booking time. It looks simple, but when a guest leaves early or a room is taken out of service, the stored numbers go stale and every change has to reshuffle other bookings. We assign a room only when the guest arrives. The second keeps a grid with a row per room and a column per night. A grid is the right tool when guests choose particular rooms, such as one with a view. Here a count per type is enough, so we count.
| Must | Should | Out of scope |
|---|---|---|
| Search, book, cancel, check in, charge, check out, housekeeping | Seasonal rates, group bookings, loyalty points | Payments, room choice by guests, multiple hotels |
Check yourself
A booking runs from 1 December to 3 December. Which nights does it cover?
- The nights of 1 and 2 December. The check-out day is not a night of the stay.
Why is a room chosen at check-in and not at booking?
- A booking for a type stays valid when a room breaks or a guest leaves early.
- Choosing late lets the hotel pick a room that is vacant and clean at that moment.
Why are dates plain days and not timestamps?
- A hotel stay is counted in calendar nights, so times and time zones add nothing except bugs.
Part 2 · Use cases
Actors and use cases
An actor is someone outside the system who uses it. A use case is one goal an actor wants to reach. The hotel has three: the guest, who searches and books, the receptionist, who checks guests in and out and adds charges, and the housekeeper, who marks rooms clean.
A use case diagram shows actors, their use cases and how those relate. Include means a use case always runs another as part of itself. Extend means an exceptional case adds steps to a base case under a condition. Check-out always includes issuing the invoice. A refusal because no room is free extends booking, and a refusal because no room is clean extends check-in.
The blue boxes are actors and the pills are use cases, with the exceptional ones in red. An arrow from an actor means the actor starts that use case. Every other arrow runs from a base case to the case it includes or the case that extends it, labelled "includes" or "extended by". Formal UML draws the extend arrow the other way, from the extension to the base; here the label carries the meaning.
Each actor sits at the head of its own group, because the three share no step. Read the diagram as a checklist of goals: each pill becomes a method or two and a few tests, and the red pills show where an unhappy path hangs off a happy one.
Flows and alternatives
Each use case gets a short written flow: a trigger, the main steps and the alternatives. Writing alternatives now is cheap. Finding them after the code exists is not.
| Use case | Main flow | Alternatives |
|---|---|---|
| Search rooms | Count the rooms of a type free on every night | Bad dates: refuse |
| Book a room type | Check every night, then record the booking | None free on some night: refuse |
| Check in | Check the day, find a clean room of the type, occupy it | Too early, too late, no clean room: refuse |
| Add a charge | Append to the folio of a checked-in guest | Not checked in, bad amount: refuse |
| Check out | Add the room nights, build the invoice, release the room | Not checked in: refuse |
| Mark a room clean | A dirty room becomes clean | Not dirty: refuse |
Every alternative is a named refusal, and each one must change nothing. A refused check-in leaves the booking and the room as they were, and we will assert that.
Two details need a decision now. The first is the order inside check-out. The room nights are added and the invoice is built before the room is released, so a failure never leaves a free room with an unpaid guest. The second is what "free" means. A room can be free for the night of 3 December on paper and still be dirty at three in the afternoon. The booking system answers the first question and the room status answers the second, and they must not be mixed.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name, a map of the work that is reported but not run, and each one becomes a real test by the end.
test.todo('a guest searches for rooms of a type'); test.todo('a guest books a room type for some nights'); test.todo('reception checks a guest in to a clean room'); test.todo('reception adds a charge to the folio'); test.todo('reception checks a guest out and issues the invoice'); test.todo('housekeeping marks a dirty room clean');
✔ a guest searches for rooms of a type (0.6465ms) # TODO ✔ a guest books a room type for some nights (0.0748ms) # TODO ✔ reception checks a guest in to a clean room (0.0571ms) # TODO ✔ reception adds a charge to the folio (0.0477ms) # TODO ✔ reception checks a guest out and issues the invoice (0.0571ms) # TODO ✔ housekeeping marks a dirty room clean (0.0556ms) # TODO ℹ tests 6 ℹ todo 6
Output (durations vary)
All six names are reported as todo, and none counts as passed. If a name never gets a test, the requirement behind it was probably missed.
What is the difference between include and extend?
- Include: the base case always runs the included case, as check-out always issues the invoice.
- Extend: an exceptional case adds steps under a condition, as the refusal for no clean room does at check-in.
Why do availability and cleanliness need separate answers?
- Availability is about future nights and is answered by counting bookings.
- Cleanliness is about a room right now and is answered by its status.
A guest tries to check in before the booked day. Which use case runs, and what is left afterwards?
- Check in runs and is refused as too early. The booking is still booked and the room is still clean.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: hotel, room type, room, guest, booking, night, check-in, folio, charge, invoice, tax, housekeeper. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| Hotel | Class Hotel | Owns the rooms and bookings and orders every step |
| Room | Class Room | Has a status with rules about what may follow what |
| Room type | A string union TypeName | Only a name and a price, and the price lives in a policy |
| Booking | Interface Booking | A record that the hotel updates |
| Folio | Class Folio | Guards the rule that a charge is a positive whole amount |
| Invoice, charge | Plain values | A folio produces them and nothing changes them |
| Rate | Interface RatePolicy | Prices change by season, so the hotel asks a policy |
| Today | Interface Calendar | Time is injected, so a test can choose the day |
| Housekeeping task | A dirty room | The status is the task, and dirtyRooms is the list |
The class diagram
A class diagram shows classes, what they hold and how they relate. Multiplicity is the number on each link end: 1..* means one or more, and 0..1 means at most one.
search(type, in, out): numberbook(guest, type, in, out)cancel(id)checkIn(id): roomaddCharge(id, text, amount)checkOut(id): InvoicedirtyRooms(), markClean(no)id, guest, typecheckIn, checkOut: Daystatus: BookingStatusroom?, arrived?number, type: TypeNamestatus: RoomStatuscheckIn(), checkOut()markClean(), block(), repair()add(description, amount)charges: Charge[]subtotal(): Paiselines, subtotaltax, totalnightly(type, night): Paiseone price per typetoday(): Day- Hotel 1 → 1..* Room
- Hotel 1 → 0..* Booking
- Booking 0..* → 0..1 Room
- Booking 1 → 1 Folio
- Folio 1 → 0..* Invoice (value)
- Hotel 1 → 1 RatePolicy (interface)
- FlatRates → RatePolicy (interface)
The skeleton in TypeScript
A diagram is only a claim until a compiler reads it. We start with days and money. A day is a string such as 2026-12-01, and every other date calculation goes through two small helpers.
export type Day = string; const MS_PER_DAY = 86_400_000; const toNumber = (d: Day): number => { const t = /^\d{4}-\d{2}-\d{2}$/.test(d) ? Date.parse(`${d}T00:00:00Z`) : NaN; if (Number.isNaN(t) || toDay(t / MS_PER_DAY) !== d) { throw new HotelError('BAD_DATES', `bad date ${d}`); } return t / MS_PER_DAY; }; const toDay = (n: number): Day => new Date(n * MS_PER_DAY).toISOString().slice(0, 10); export const addDays = (d: Day, n: number): Day => toDay(toNumber(d) + n); export const nightsBetween = (from: Day, to: Day): number => toNumber(to) - toNumber(from); // Every night of a stay: [from, to) as a list of days. export const nightsOf = (from: Day, to: Day): Day[] => { const n = nightsBetween(from, to); if (n < 1) { throw new HotelError('BAD_DATES', 'stay at least one night'); } return Array.from({ length: n }, (_, i) => addDays(from, i)); };
nightsOf lists the nights of a stay and refuses a stay shorter than one night. The pattern in toNumber keeps dates in one shape. Date.parse alone is not enough, because it accepts a day that does not exist and rolls it forward: 30 February becomes 2 March. So toNumber turns the number back into a day and compares it with the input, which refuses every date that does not round-trip. A run shows both halves.
const raw = Date.parse('2026-02-30T00:00:00Z'); const rolled = new Date(raw).toISOString(); console.log(`Date.parse reads 30 February as ${rolled}`); for (const [from, to] of [['2026-02-30', '2026-03-05']] as const) { try { nightsOf(from, to); console.log('accepted'); } catch (e) { console.log(`${from} refused: ${(e as Error).message}`); } }
Date.parse reads 30 February as 2026-03-02T00:00:00.000Z 2026-02-30 refused: bad date 2026-02-30
Output
Without the comparison, a stay from 30 February to 5 March would have been accepted as three nights from 2 March. Errors come next.
export type HotelCode = | 'BAD_DATES' | 'BAD_AMOUNT' | 'NO_AVAILABILITY' | 'UNKNOWN_BOOKING' | 'UNKNOWN_ROOM' | 'BAD_STATE' | 'TOO_EARLY' | 'TOO_LATE' | 'NO_CLEAN_ROOM' | 'ROOM_NOT_READY'; export class HotelError extends Error { readonly code: HotelCode; constructor(code: HotelCode, message: string) { super(message); this.name = 'HotelError'; this.code = code; } }
Part 4 · Room status and check-out
Four room statuses
A state machine lists the states, the events that cause moves and the events a state refuses. A room has four statuses. vacantClean means a guest could be given it now. occupied means a guest is in it. vacantDirty means the last guest has left and nobody has cleaned it. outOfOrder means it cannot be offered until it is repaired.
Watch for a dirty room refusing the next guest
Read it as steps
A room is only offered at check-in when it is vacant and clean.
The scene follows room 201 for one guest and refuses a check-in in the middle. After check-out the room is dirty, and trying to occupy it is refused with ROOM_NOT_READY until housekeeping marks it clean. The hotel itself never offers a dirty room. It picks only rooms that are clean, and when there are none it answers NO_CLEAN_ROOM. The room's own refusal is a second line of defence.
The full picture is easier to read as a table: for each status, what each action does.
Check-out in order
Check-out is the step where money moves, so its order matters. Follow a guest in room 201 who booked 1 to 3 December and added room service of ₹450 during the stay.
Watch for the room nights being added only at check-out
Read it as steps
The folio gets the room nights, the invoice adds tax, and the room goes on the cleaning list.
The hotel works out how many nights were stayed, asks the rate policy for each night and adds those charges to the folio. Then the invoice is built from the folio, with tax on top. Only after that does the room become vacant and dirty. If any earlier step were to fail, the room would still be occupied and the guest would still be on record, so nothing is half done.
| Step | Can fail with | Changes anything? |
|---|---|---|
| Find the booking | UNKNOWN_BOOKING | No |
| The guest is checked in | BAD_STATE | No |
| Add the room nights | Nothing |
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. This one searches for a double room, books it, checks the guest in, adds room service and checks out two nights later.
const { hotel, calendar } = rig('2026-12-01'); const free = () => hotel.search('double', '2026-12-01', '2026-12-03'); console.log(`doubles free for 1 to 3 Dec: ${free()}`); const b = hotel.book('Meera Rao', 'double', '2026-12-01', '2026-12-03'); console.log(`booked ${b.id}, doubles free now: ${free()}`); console.log(`checked in to room ${hotel.checkIn(b.id)}`); hotel.addCharge(b.id, 'Room service', 45000); calendar.set('2026-12-03'); const invoice = hotel.checkOut(b.id); for (const l of invoice.lines) { console.log(`${l.description}: ${rupees(l.amount)}`); } console.log(`subtotal ${rupees(invoice.subtotal)}`); console.log(`tax ${rupees(invoice.tax)}`); console.log(`total ${rupees(invoice.total)}`); console.log(`to clean: ${hotel.dirtyRooms().join(', ')}`);
doubles free for 1 to 3 Dec: 2 booked BK-1, doubles free now: 1 checked in to room 201 Room service: ₹450.00 Room 201, night of 2026-12-01: ₹3,000.00 Room 201, night of 2026-12-02: ₹3,000.00 subtotal ₹6,450.00 tax ₹645.00 total ₹7,095.00 to clean: 201
Output
Two doubles were free at the start and one after the booking. The guest was given room 201, the first clean double. The invoice has the room service line and two room nights of ₹3,000 each, so the subtotal is ₹6,450.00. The 10 per cent tax is ₹645.00 and the total ₹7,095.00. Room 201 is now on the cleaning list.
Why does the hotel pick only clean rooms, when the room already refuses a dirty check-in?
- Picking a clean room lets the hotel say
NO_CLEAN_ROOM, which tells reception what to do next. - The room's own refusal is a second line of defence if some other code calls it directly.
Why is the room released after the invoice is built?
- Everything that could go wrong happens first, so a failure never leaves a released room with an unbilled guest.
Part 5 · Code: availability, stays and folios
Counting free rooms
Everything below leans on the day helpers, so we run them on the awkward cases first: a year boundary, a leap year and a February without a 29th.
const stays = [ ['2026-12-30', '2027-01-02'], ['2028-02-27', '2028-03-01'], ['2026-02-27', '2026-03-01'], ] as const; for (const [from, to] of stays) { const n = nightsBetween(from, to); console.log(`${from} to ${to}: ${n} nights: ${nightsOf(from, to)}`); }
2026-12-30 to 2027-01-02: 3 nights: 2026-12-30,2026-12-31,2027-01-01 2028-02-27 to 2028-03-01: 3 nights: 2028-02-27,2028-02-28,2028-02-29 2026-02-27 to 2026-03-01: 2 nights: 2026-02-27,2026-02-28
Output
The stay across new year has three nights, the leap-year stay includes the night of 29 February 2028 and the same dates in 2026 have only two nights. Counting nights as a difference of day numbers gets all three right without a rule for each.
Availability is a count, not a grid. A room type has a capacity, which is the number of rooms of that type. On any one night, the bookings of that type that are booked or checked in hold some of them. The free rooms for a stay are the minimum over its nights of capacity minus held.
// Rooms of this type still free on every night of the stay. search(type: TypeName, checkIn: Day, checkOut: Day): number { const capacity = this.#rooms.filter((r) => r.type === type).length; const held = (night: Day) => [...this.#bookings.values()].filter( (b) => b.type === type && (b.status === 'booked' || b.status === 'checkedIn') && b.checkIn <= night && night < b.checkOut, ).length; const nights = nightsOf(checkIn, checkOut); return Math.min(...nights.map((n) => capacity - held(n))); } book(guest: string, type: TypeName, checkIn: Day, checkOut: Day) { if (this.search(type, checkIn, checkOut) < 1) { throw new HotelError('NO_AVAILABILITY', `no ${type} room free`); } return this.#create(guest, type, checkIn, checkOut); } #create(guest: string, type: TypeName, checkIn: Day, checkOut: Day) { const b: Booking = { id: this.#nextId(), guest, type, checkIn, checkOut, folio: new Folio(), status: 'booked', }; this.#bookings.set(b.id, b); return b; }
The held function counts bookings that cover a night. A booking covers the night if its check-in is on or before the night and its check-out is after it, which is a half-open range. That is why a guest leaving on 3 December and a guest arriving on 3 December do not collide: the first stay does not cover the night of the 3rd. The minimum matters too. A type can be free on every night but one, and that one night decides.
Tests for availability
Each test is a sentence about the hotel that a manager would recognise, and a test name that a manager cannot read is usually a test of the code and not of the rule.
test('search counts the rooms free on every night', () => { const { hotel } = rig(); hotel.book('Meera', 'double', '2026-12-01', '2026-12-03'); assert.equal(hotel.search('double', '2026-12-01', '2026-12-03'), 1); assert.equal(hotel.search('double', '2026-12-03', '2026-12-05'), 2); assert.equal(hotel.search('single', '2026-12-01', '2026-12-03'), 2); }); test('the busiest night decides', () => { const { hotel } = rig(); hotel.book('Meera', 'double', '2026-12-01', '2026-12-03'); hotel.book('Imran', 'double', '2026-12-02', '2026-12-04'); assert.equal(hotel.search('double', '2026-12-01', '2026-12-02'), 1); assert.equal(hotel.search('double', '2026-12-01', '2026-12-04'), 0); }); test('a booking beyond the rooms is refused', () => { const { hotel } = rig(); hotel.book('Meera', 'double', '2026-12-01', '2026-12-03'); hotel.book('Imran', 'double', '2026-12-01', '2026-12-03'); assert.throws( () => hotel.book('Leela', 'double', '2026-12-02', '2026-12-04'), { code: 'NO_AVAILABILITY' }, ); assert.equal(hotel.search('double', '2026-12-03', '2026-12-04'), 2); });
The fourth test, which the page does not show, books two stays that touch on 3 December and shows that they fit in one suite. The fifth lists the bad dates, including 30 February in 2026 and in 2028, and checks that the refusal names the date.
✔ search counts the rooms free on every night (2.3627ms) ✔ the busiest night decides (0.1627ms) ✔ a booking beyond the rooms is refused (0.5282ms) ✔ back-to-back stays share a room (0.1224ms) ✔ bad dates are refused (0.2409ms) ✔ cancelling frees the nights (0.1895ms) ℹ tests 6 ℹ pass 6 ℹ fail 0
Output (durations vary)
A booking beyond the rooms is refused, and the very next line checks that the hotel still has two doubles free on the night after, so the refusal changed nothing.
Check-in
Check-in applies the rules in the order the requirements gave them. The booking must be booked, the day must be inside the stay, and only then does the hotel look for a room.
checkIn(id: string): string {
const b = this.#booking(id);
this.#expect(b, 'booked');
const today = this.#calendar.today();
if (today < b.checkIn) {
throw new HotelError('TOO_EARLY', `arrival is ${b.checkIn}`);
}
if (today >= b.checkOut) {
throw new HotelError('TOO_LATE', 'the booked stay is over');
}
const room = this.#rooms.find(
(r) => r.type === b.type && r.status === 'vacantClean',
);
if (!room) {
throw new HotelError('NO_CLEAN_ROOM', 'no clean room yet');
}
room.checkIn();
b.status = 'checkedIn';
b.room = room.number;
b.arrived = today;
return room.number;
}
addCharge(id: string, description: string, amount: Paise): void {
const b = this.#booking(id);
this.#expect(b, 'checkedIn');
b.folio.add(description, amount);
}The three checks before the search throw without touching anything. The search looks for a room of the booked type whose status is vacant and clean. Only after that does the room change status and the booking record its room and its arrival day. The arrival day matters later, because the bill counts nights from it. A guest who arrives a day after the booked day is therefore billed from the day of arrival, which is our rule that nights not slept are not billed.
Check-out and the folio
Check-out counts the nights stayed from the arrival day to today, with a minimum of one so that a same-day departure still pays for a night.
checkOut(id: string): Invoice {
const b = this.#booking(id);
this.#expect(b, 'checkedIn');
const arrived = b.arrived!;
const today = this.#calendar.today();
const stayed = Math.max(1, nightsBetween(arrived, today));
for (const night of nightsOf(arrived, addDays(arrived, stayed))) {
const rate = this.#rates.nightly(b.type, night);
b.folio.add(`Room ${b.room}, night of ${night}`, rate);
}
this.#room(b.room!).checkOut();
b.status = 'checkedOut';
return invoiceFor(b.folio);
}The folio holds the charges, and the invoice is computed from it. The folio refuses a charge that is not a positive whole number of paise.
export interface Charge { description: string; amount: Paise; } // In our model: one flat tax on the bill, made up for this chapter. export const TAX_PERCENT = 10; export class Folio { readonly #charges: Charge[] = []; add(description: string, amount: Paise): void { if (!Number.isInteger(amount) || amount <= 0) { throw new HotelError('BAD_AMOUNT', 'charge a positive amount'); } this.#charges.push({ description, amount }); } get charges(): Charge[] { return this.#charges.map((c) => ({ ...c })); } subtotal(): Paise { return this.#charges.reduce((sum, c) => sum + c.amount, 0); } }
The invoice adds the tax and rounds it to a whole paisa, halves up.
export interface Invoice { lines: Charge[]; subtotal: Paise; tax: Paise; total: Paise; } export const invoiceFor = (folio: Folio): Invoice => { const subtotal = folio.subtotal(); const tax = Math.round((subtotal * TAX_PERCENT) / 100); return { lines: folio.charges, subtotal, tax, total: subtotal + tax }; };
Tests for stays and bills
The stay tests check an early and a late arrival, and the waiting guest: every double room is dirty, so check-in is refused and changes nothing, and a room that is then cleaned is given at once.
test('an early or late arrival is refused and changes nothing', () => { const { hotel, calendar, rooms } = rig('2026-11-30'); const b = hotel.book('Meera', 'double', '2026-12-01', '2026-12-03'); assert.throws(() => hotel.checkIn(b.id), { code: 'TOO_EARLY' }); calendar.set('2026-12-03'); assert.throws(() => hotel.checkIn(b.id), { code: 'TOO_LATE' }); assert.equal(b.status, 'booked'); assert.equal(rooms[2]!.status, 'vacantClean'); }); test('a booked guest waits while every room is dirty', () => { const { hotel, calendar } = rig(); const a = hotel.book('Meera', 'double', '2026-12-01', '2026-12-03'); const b = hotel.book('Imran', 'double', '2026-12-01', '2026-12-03'); const c = hotel.book('Leela', 'double', '2026-12-03', '2026-12-05'); hotel.checkIn(a.id); hotel.checkIn(b.id); calendar.set('2026-12-03'); hotel.checkOut(a.id); hotel.checkOut(b.id); assert.throws(() => hotel.checkIn(c.id), { code: 'NO_CLEAN_ROOM' }); assert.equal(c.status, 'booked'); hotel.markClean('202'); assert.equal(hotel.checkIn(c.id), '202'); });
✔ check-in picks a clean room of the booked type (1.6302ms) ✔ an early or late arrival is refused and changes nothing (1.0332ms) ✔ a booked guest waits while every room is dirty (0.383ms) ✔ a room moves through its statuses in order (0.1581ms) ✔ check-out needs a stay, and only once (0.177ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
The bill tests check the invoice, the early check-out and the rounding.
test('the invoice adds room nights, extras and tax', () => { const { hotel, calendar } = rig(); const b = hotel.book('Meera', 'double', '2026-12-01', '2026-12-03'); hotel.checkIn(b.id); hotel.addCharge(b.id, 'Room service', 45000); calendar.set('2026-12-03'); const inv = hotel.checkOut(b.id); assert.equal(inv.lines.length, 3); assert.equal(inv.subtotal, 645000); assert.equal(inv.tax, 64500); assert.equal(inv.total, 709500); }); test('checking out early bills only the nights stayed', () => { const { hotel, calendar } = rig(); const b = hotel.book('Meera', 'double', '2026-12-01', '2026-12-04'); hotel.checkIn(b.id); calendar.set('2026-12-02'); assert.equal(hotel.checkOut(b.id).subtotal, 300000); assert.equal(hotel.search('double', '2026-12-02', '2026-12-04'), 2); });
✔ the invoice adds room nights, extras and tax (2.5299ms) ✔ checking out early bills only the nights stayed (0.177ms) ✔ a same-day check-out still bills one night (0.1156ms) ✔ tax rounds half up to a whole paisa (0.1319ms) ✔ bad charges are refused and leave the folio alone (0.5686ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
Part 6 · Extensions and trade-offs
Every use case, tested
The use case lesson left six test.todo names. With the hotel in place, each becomes a real test that drives it the way its actor would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules.
test('a guest searches for rooms of a type', () => { const { hotel } = rig(); assert.equal(hotel.search('suite', '2026-12-01', '2026-12-03'), 1); }); test('a guest books a room type for some nights', () => { const { hotel } = rig(); const b = hotel.book('Meera', 'suite', '2026-12-01', '2026-12-03'); assert.equal(b.status, 'booked'); assert.equal(hotel.search('suite', '2026-12-01', '2026-12-03'), 0); }); test('reception checks a guest in to a clean room', () => { const { hotel } = rig(); const b = hotel.book('Meera', 'single', '2026-12-01', '2026-12-02'); assert.equal(hotel.checkIn(b.id), '101'); }); test('reception adds a charge to the folio', () => { const { hotel } = rig(); const b = hotel.book('Meera', 'single', '2026-12-01', '2026-12-02'); hotel.checkIn(b.id); hotel.addCharge(b.id, 'Laundry', 30000); assert.deepEqual(b.folio.charges, [ { description: 'Laundry', amount: 30000 }, ]); });
The other two cover check-out with its invoice and housekeeping marking a room clean.
✔ a guest searches for rooms of a type (1.751ms) ✔ a guest books a room type for some nights (0.2221ms) ✔ reception checks a guest in to a clean room (0.179ms) ✔ reception adds a charge to the folio (0.56ms) ✔ reception checks a guest out and issues the invoice (0.2295ms) ✔ housekeeping marks a dirty room clean (0.175ms) ℹ tests 6 ℹ pass 6 ℹ fail 0 ℹ todo 0
Output (durations vary)
Six pass and no todo is left. The whole suite, including the earlier tests, also passes.
ℹ tests 22 ℹ pass 22 ℹ fail 0 ℹ todo 0
Output: whole suite
Seasonal rates
Prices that depend on the date are the reason the hotel asks a policy. A seasonal policy wraps another policy and adds a percentage on nights inside a peak range. This is the decorator idea from the patterns chapter: an object that has the same interface as the one it wraps and adds behaviour to it. The rest of this lesson lives in a copy of the project with the new files added.
// Wraps another policy and adds a percentage on peak nights. export class SeasonalRates implements RatePolicy { readonly #base: RatePolicy; readonly #from: Day; readonly #to: Day; readonly #percent: number; constructor(base: RatePolicy, from: Day, to: Day, percent: number) { this.#base = base; this.#from = from; this.#to = to; this.#percent = percent; } nightly(type: TypeName, night: Day): Paise { const price = this.#base.nightly(type, night); if (night < this.#from || night > this.#to) return price; return Math.round((price * (100 + this.#percent)) / 100); } }
The hotel did not change at all, which is the point of the strategy. Only the object passed in when the hotel is built is different. The tests check the last peak night and the first normal one, and a stay that crosses the end of the season.
const base = new FlatRates({ single: 200000, double: 300000, suite: 800000, }); const peak = new SeasonalRates(base, '2026-12-20', '2026-12-26', 50); test('peak nights cost more and others do not', () => { assert.equal(peak.nightly('double', '2026-12-26'), 450000); assert.equal(peak.nightly('double', '2026-12-27'), 300000); }); test('a stay across the edge of the season mixes both rates', () => { const { hotel, calendar } = rig('2026-12-26', peak); const b = hotel.book('Meera', 'double', '2026-12-26', '2026-12-28'); hotel.checkIn(b.id); calendar.set('2026-12-28'); assert.equal(hotel.checkOut(b.id).subtotal, 750000); });
✔ peak nights cost more and others do not (0.5147ms) ✔ a stay across the edge of the season mixes both rates (1.3569ms) ✔ a group booking holds several rooms or none (0.5868ms) ✔ points add up across stays (0.4676ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output: the extension tests (durations vary)
The stay from 26 to 28 December pays the peak price for the night of the 26th and the normal price for the 27th. That is ₹4,500 and ₹3,000, a subtotal of ₹7,500.
Group bookings and loyalty points
A group booking holds several rooms of a type in one go, and it is all or nothing. The hotel checks that enough rooms are free for every night, and only then creates the bookings.
bookGroup(
guest: string, type: TypeName, checkIn: Day, checkOut: Day,
rooms: number,
): Booking[] {
if (this.search(type, checkIn, checkOut) < rooms) {
throw new HotelError('NO_AVAILABILITY', 'too few rooms');
}
return Array.from({ length: rooms }, () =>
this.#create(guest, type, checkIn, checkOut));
}test('a group booking holds several rooms or none', () => { const { hotel } = rig(); const rooms = hotel.bookGroup( 'Rao family', 'double', '2026-12-01', '2026-12-03', 2, ); assert.equal(rooms.length, 2); assert.equal(hotel.search('double', '2026-12-01', '2026-12-03'), 0); const refused = () => hotel.bookGroup('Shah', 'single', '2026-12-01', '2026-12-03', 3); assert.throws(refused, { code: 'NO_AVAILABILITY' }); assert.equal(hotel.search('single', '2026-12-01', '2026-12-03'), 2); });
The second half of the test refuses a group of three singles when there are only two, and then checks that the two singles are still free. Loyalty points use an observer: the hotel keeps a list of listeners and calls each one when a guest checks out, so the points code needs no change to the check-out code.
// In our model: one point for each full 100 rupees on the invoice. export class Loyalty { readonly #points = new Map<string, number>(); attach(hotel: Hotel): void { hotel.on(({ booking, invoice }) => { const earned = Math.floor(invoice.total / 10000); const total = this.points(booking.guest) + earned; this.#points.set(booking.guest, total); }); } points(guest: string): number { return this.#points.get(guest) ?? 0; } }
test('points add up across stays', () => { const { hotel, calendar } = rig(); const loyalty = new Loyalty(); loyalty.attach(hotel); const one = hotel.book('Meera', 'double', '2026-12-01', '2026-12-03'); hotel.checkIn(one.id); hotel.addCharge(one.id, 'Room service', 45000); calendar.set('2026-12-03'); hotel.checkOut(one.id); assert.equal(loyalty.points('Meera'), 70); const two = hotel.book('Meera', 'single', '2026-12-03', '2026-12-04'); hotel.checkIn(two.id); calendar.set('2026-12-04'); hotel.checkOut(two.id); assert.equal(loyalty.points('Meera'), 92); assert.equal(loyalty.points('Imran'), 0); });
ℹ tests 26 ℹ pass 26 ℹ fail 0 ℹ todo 0
Output: whole extended suite
The first stay earns 70 points, one for each full ₹100 of ₹7,095. The second earns 22, one for each full ₹100 of ₹2,200, so the total is 92. The whole extended project, with the original tests, passes.
Where this design is weak
Every design has costs. The count per type cannot say that a guest wants a particular room, and the grid we rejected would be needed for that. Capacity counts every room of a type, including one that is out of order, so a long repair would need a capacity that changes from night to night. A booking is a mutable record that the hotel edits, which is simple but lets a careless caller change a status, and a stricter design would hide it behind methods. Availability scans every booking for every night, which is fine for hundreds and slow for millions, and an index by type and night would fix that. There are no time zones and no times of day, so a late check-out fee cannot be modelled. And the model has one process: two receptionists booking the last room at the same moment would need the lock that the parking lot chapter teaches.
| Term | Meaning |
|---|---|
| Folio | The running list of charges a guest owes during a stay |
| Half-open range | A range that includes its start and excludes its end |
| Strategy | An object that supplies one varying decision, such as a price |
| Decorator | A wrapper with the same interface that adds behaviour |
| Observer | A list of listeners that an object calls when something happens |
Why did the seasonal rates not need any change to Hotel?
- The hotel only calls
nightlyon a policy, so a new policy with the same interface slots in.
Why must a group booking check every night before it creates anything?
- If it created bookings one by one, a late failure would leave some rooms held for a group that never got them.
All chapters · Previous: Chess: Board, Pieces, Legal Moves and Game End