Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 7
Module 4 · Design problems I: parking, elevators and libraries · Chapter 7 of 28
Parking Lot: Floors, Spots, Tickets and Fees
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps and Design Patterns in TypeScript: Creational, Structural and Behavioural. Next up: Elevator System: Cars, Hall Calls and Dispatching.
Part 1 · Requirements
What the lot must do
A mall or office-tower parking lot looks simple until you list its rules: which vehicle fits which spot, when the clock starts, and what happens at the exit when the ticket is gone. This chapter builds that lot as small classes you can run and test.
A requirement is a sentence about the system that someone can check. Functional requirements say what the system does. We write them first, in plain words, before any class exists. For a Hyderabad mall with a three-floor car park, they are these.
- A lot has several floors. Each floor has spots of three sizes: small, medium and large.
- The vehicles are bikes, cars and trucks. A bike fits any spot, a car fits a medium or large spot, and a truck needs a large spot.
- At the entry gate the driver gets a ticket that names a spot and the entry time. The gate picks the smallest free spot that fits, on the lowest floor that has one.
- If no spot fits, the gate refuses the vehicle and says why.
- At the exit the driver pays a fee that depends on the vehicle type and the time spent. Only a paid ticket opens the exit.
- A driver who lost the ticket pays a flat penalty, and then the exit opens.
- A display board at each gate shows how many spots of each size are free.
- The admin chooses the floors, the spot counts and the rates before the lot opens.
Notice what is missing. Nothing says how spots are stored, which screen the driver sees or how card payments work. Requirements describe behaviour, and the design decides the rest.
A prompt as short as "design a parking lot" leaves these rules open, so the list comes from questions. Ask the ones whose answers change a class or a method, and write each answer down as a rule.
| Question |
|---|
Numbers, quality and scope
Non-functional requirements describe how well the system behaves rather than what it does. Three matter here. The lot must never give one spot to two cars, even when two gates are busy at once. Fees must be reproducible, so the same entry and exit times always give the same amount. And the entry decision must stay quick as the lot grows, so we do not scan every spot for every car.
The rates below are made up for this chapter and are not any real lot's tariff.
| Rule | Value in our model |
|---|---|
| Free period | a stay of 15 minutes or less |
| Bike | ₹10 per started hour |
| Car | ₹20 per started hour |
| Truck | ₹40 per started hour |
| Lost ticket | flat ₹500 |
A started hour means any part of an hour counts as a full one, so 61 minutes is two hours. The free period is a threshold, not a discount: a stay of 16 minutes pays one full hour. Money is held as integer paise (a hundredth of a rupee), because decimals such as 0.1 + 0.2 do not add up exactly in floating point. We format only at the edge, for display.
A good scoping habit is a three-column list. It keeps the first version small and shows others that you chose on purpose.
| Must | Should | Out of scope |
|---|---|---|
| Spot fit, tickets, fees, lost ticket, display board | Cap on the daily fee, EV charging spots |
Check yourself
A car stays 61 minutes under our tariff. How many hours does it pay for, and why?
- Two hours: any part of an hour counts as a full started hour.
- The free period is a threshold: a stay of 15 minutes or less is free, but 61 minutes pays both hours in full.
Why hold money as integer paise?
- Binary floating point cannot represent most decimal fractions exactly: in JavaScript 0.1 + 0.2 prints 0.30000000000000004.
- Integers add exactly; the rupee sign and decimals appear only when printing.
The answer to "are spots booked ahead of time?" changes from no to yes. Which parts of the model must grow?
- A ticket, or a new booking object, needs a state before the car arrives, plus an expiry for no-shows.
- Allocation must skip spots that are held for a booking, so the floor's free set is no longer the whole story.
Part 2 · Use cases
Actors and use cases
An actor is someone or something outside the system that uses it. A use case is one goal an actor wants to reach, such as "pay and exit". The parking lot has three actors: the driver, an attendant who handles exceptions at the gate, and an admin who configures the lot.
A use case diagram shows actors, the use cases each one starts, and how use cases relate. Two relations show up often. Include means a use case always runs another one as part of itself. Extend means an optional or exceptional case that adds steps to a base case under some condition. Here "calculate fee" is included in "pay and exit", while "refuse: lot full" and "lost ticket" extend the cases they interrupt.
In this diagram the actors are the blue boxes and the use cases are the pills, with the exceptional cases 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, as a dashed arrow marked «extend». The meaning is the same; when you sketch one by hand, use the UML direction or say which one you chose.
Read the diagram as a checklist of goals, not as a design. Each pill will become one or two methods and a few tests, and the "extended by" arrows tell you where the unhappy paths hang off the happy one.
Flows and alternatives
Each use case gets a short written flow: a trigger, the main steps and the alternatives. Writing the alternatives now is cheap. Finding them after the code exists is not.
| Use case | Main flow | Alternatives |
|---|---|---|
| Park a vehicle | Driver arrives; gate finds the smallest fitting free spot; spot is claimed; ticket is printed | No spot fits: refuse with a reason |
| Pay and exit | Driver presents ticket; fee is computed from the stay; driver pays; exit opens; spot is freed | Unpaid ticket: exit stays shut. Ticket lost: flat fee, then exit |
| Handle lost ticket | Attendant marks the ticket lost; the flat fee replaces the hourly fee | Ticket already exited: refuse |
| Read display board | Gate shows free spots per size | None |
Alternatives are where requirements get argued, so write them as decisions with a name. "Lot full" is a refusal with a reason the driver can read, not a crash and not a silent hang. "Lost ticket" is a state change that the attendant triggers, and it has its own fee, so the tariff never needs to know that tickets can be lost.
Two details deserve a decision now. First, when does the clock stop? In our model the fee is computed when the driver pays, and exit follows payment. Second, who frees the spot? Exit does, not payment, because a paid car is still parked until it leaves.
Use cases as test names
A use case is easy to turn into a test name, and node:test can hold a name without a body. test.todo registers a test that is reported but not run. A list of todos at the start is a map of the work, and each one turns into a real test as the code lands.
test.todo('driver parks a car and gets a ticket'); test.todo('driver pays at exit and the spot is freed'); test.todo('gate refuses entry when no spot fits'); test.todo('attendant marks a ticket lost, flat fee applies'); test.todo('exit is refused for an unpaid ticket'); test.todo('admin sets up floors and the tariff');
✔ driver parks a car and gets a ticket (0.7542ms) # TODO ✔ driver pays at exit and the spot is freed (0.1427ms) # TODO ✔ gate refuses entry when no spot fits (0.1279ms) # TODO ✔ attendant marks a ticket lost, flat fee applies (0.066ms) # TODO ✔ exit is refused for an unpaid ticket (0.1173ms) # TODO ✔ admin sets up floors and the tariff (0.1025ms) # TODO ℹ tests 6 ℹ todo 6
Output (durations vary)
Every name is reported as a todo, and the summary counts six of them with no failures. Later lessons replace these names with tests that pass. If a name here never gets a test, the requirement behind it was probably missed.
What is the difference between include and extend in a use case diagram?
- Include: the base case always runs the included case, like fee calculation inside pay and exit.
- Extend: an optional or exceptional case adds steps to the base case, like lot full during parking.
Which of these is an actor: the display board, the attendant, the tariff?
- The attendant. An actor is outside the system and has a goal; the board and tariff are parts of the system.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: lot, floor, spot, vehicle, ticket, tariff, payment, gate, display board. Not every noun becomes a class. A useful test is whether the thing has its own behaviour and rules to protect.
| Noun | Decision | Why |
|---|---|---|
| Lot | Class ParkingLot | Chooses a spot across floors |
| Floor | Class Floor | Owns the free spots of its level |
| Spot | Value: an id and a size | No behaviour of its own, so no class |
| Vehicle | Value: plate and a type | Only its type affects the design |
| Ticket | Class Ticket | Has a lifecycle with rules |
| Tariff | Interface Tariff | Rates change; a strategy lets them be swapped |
| Payment | Field paid on the ticket | One method of payment so far |
| Display board | Method board() | A read of the free counts, not a class |
Notice the nouns that did not make the list. The gate and the booth are places where the service is called from, not objects with state, so they do not need classes yet. If the lot later has gates that can break or queue, a Gate class earns its place. Add a class when there is a rule to put in it.
The class diagram
A class diagram shows classes, what they hold and how they relate. The numbers on the links are multiplicity: how many objects sit at each end. 1..* means one or more, * means zero or more, and 0..1 means at most one.
park(plate, type): Ticketpay(ticketId): Paiseexit(ticketId)reportLost(ticketId)peek(type): spotId?occupy(spotId)release(spotId)board(): countslevel: numberfree: Map<size, Set<spotId>>peek(size)occupy(spotId)id: stringsize: small | medium | largeid, plate, typespotId, issuedAtstate: TicketStatepaid: Paisefee(type, minutes): Paiserate per started hourgraceMinutes- ParkingService 1 → 1 ParkingLot
- ParkingLot 1 → 1..* Floor
- Floor 1 → * Spot (value)
- ParkingService 1 → 0..* Ticket
- Ticket * → 1 Spot (value)
- ParkingService 1 → 1 Tariff (interface)
- HourlyTariff → Tariff (interface)
Read the links like sentences. A lot has one or more floors. A floor has many spots. A service issues zero or more tickets. A ticket names exactly one spot, while over a day the same spot appears on many tickets. The service depends on a Tariff interface and knows nothing about hourly rates; HourlyTariff is one way to fill that slot.
The skeleton in TypeScript
A diagram is only a claim until a compiler reads it. We write the shared types and the error class first, then check them with tsc. The vehicle and spot types are plain unions, because enum is not erasable syntax and Node's type stripping rejects it.
export const SIZES = ['small', 'medium', 'large'] as const; export type SpotSize = (typeof SIZES)[number]; export type VehicleType = 'bike' | 'car' | 'truck'; export type Paise = number; // Sizes a vehicle may use, smallest first. export const FITS: Record<VehicleType, readonly SpotSize[]> = { bike: ['small', 'medium', 'large'], car: ['medium', 'large'], truck: ['large'], };
Each vehicle lists the sizes it may use, smallest first. That one table drives allocation, so adding a vehicle later means adding a row.
export type ParkingCode = | 'LOT_FULL' | 'UNKNOWN_TICKET' | 'NOT_PAID' | 'BAD_STATE' | 'SPOT_TAKEN' | 'UNKNOWN_SPOT'; export class ParkingError extends Error { readonly code: ParkingCode; constructor(code: ParkingCode, message: string) { super(message); this.name = 'ParkingError'; this.code = code; } }
Every failure the lot can report is a ParkingError with a code from a closed set. Callers and tests branch on the code, never on the message text. Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
Why is Spot a value and not a class here?
- It has only an id and a size and no rules of its own; the floor guards whether it is free.
What does the multiplicity * to 1 between Ticket and Spot tell you?
- Each ticket names exactly one spot.
- Over a day, the same spot is named by many tickets, one after another.
Part 4 · Entry to exit
The ticket lifecycle
A ticket moves through a small set of states, and only some moves are legal. A state machine lists the states, the events that cause moves, and the rejected events. Drawing it first turns many if statements into one table.
Our ticket starts as active when the car enters. Paying moves it to paid, and exit moves a paid ticket to exited, which is final. If the driver reports the ticket lost, it moves to lost, and paying the flat fee moves it on to paid.
Watch for the exit gate refusing a ticket that is still active
Read it as steps
A ticket must be paid before it can exit; a lost ticket pays the flat fee first.
The scene shows the point of the table. Exit is not allowed from active, and the lot answers NOT_PAID instead of opening the gate. The same table rejects a second exit with BAD_STATE, because nothing leaves exited.
The code is a lookup. Each state maps events to the next state, and a missing entry means the move is refused.
export type TicketState = 'active' | 'paid' | 'exited' | 'lost'; export type TicketEvent = 'pay' | 'exit' | 'lost'; type Moves = Partial<Record<TicketEvent, TicketState>>; const NEXT: Record<TicketState, Moves> = { active: { pay: 'paid', lost: 'lost' }, lost: { pay: 'paid' }, paid: { exit: 'exited' }, exited: {}, };
One car, from entry to exit
Now follow a single car through the whole system. The driver arrives, and the entry gate, which is the service, asks the lot for the best spot. The lot walks the sizes a car may use, medium first, and for each size asks each floor in order. The first free spot found wins.
Watch for the gate asking the lot, which asks each floor for a medium spot
Read it as steps
The gate asks the lot, the lot asks each floor, and the spot is claimed before the ticket is written.
Two things are worth noticing. The lot only suggests a spot with peek; claiming it is a separate occupy call. And the ticket is written after the claim, so a ticket never names a spot nobody holds. Both facts come back in the last lesson, where two gates make the gap between peek and occupy matter.
The service code is short because the lot and ticket do the real work.
export class ParkingService { readonly #d: Deps; readonly #tickets = new Map<string, Ticket>(); constructor(deps: Deps) { this.#d = deps; } park(plate: string, type: VehicleType): Ticket { const spot = this.#d.lot.peek(type); if (spot === undefined) { throw new ParkingError('LOT_FULL', `no spot for a ${type}`); } this.#d.lot.occupy(spot); return this.issue(plate, type, spot); } // Writes the ticket for a spot that is already claimed. issue(plate: string, type: VehicleType, spotId: string): Ticket { const id = this.#d.ids.next('T'); const at = this.#d.clock.now(); const ticket = new Ticket(id, plate, type, spotId, at); this.#tickets.set(id, ticket); return ticket; }
Run the driver
The driver is the small demo.ts script from the approach chapter, which runs the core flow once and prints what happened. This one parks a car on a one-floor lot with a fake clock, lets 95 minutes pass, pays and exits.
const clock = new FakeClock(); const lot = new ParkingLot([ new Floor(1, { small: 1, medium: 2, large: 1 }), ]); const rates = { bike: 1000, car: 2000, truck: 4000 }; const tariff = new HourlyTariff(rates, 15); const svc = new ParkingService({ lot, tariff, clock, ids: new CounterIds(), lostFee: 50000, }); const ticket = svc.park('DEMO-0001', 'car'); console.log(`ticket ${ticket.id} spot ${ticket.spotId}`); console.log('board', JSON.stringify(lot.board())); clock.advanceMinutes(95); const fee = svc.pay(ticket.id); console.log(`paid ${rupees(fee)} after 95 minutes`); svc.exit(ticket.id); console.log(`state ${ticket.state}`); console.log('board', JSON.stringify(lot.board()));
ticket T-1 spot F1-M1 board {"small":1,"medium":1,"large":1} paid ₹40.00 after 95 minutes state exited board {"small":1,"medium":2,"large":1}
Output
The car got medium spot F1-M1, because medium is the smallest size a car fits. While it was parked the board showed one medium spot left, and after exit it was back to two. At ₹20 per started hour, 95 minutes is two hours, so the fee is ₹40.00. The FakeClock made the 95 minutes pass instantly, and the answer will be the same on every run.
In the demo, why does the car get F1-M1 and not a large spot?
- The lot tries sizes smallest first, and medium is the smallest size a car fits.
Which state does the ticket end in, and what freed the spot?
- It ends in
exited; the exit call releases the spot back to the floor's free set.
Part 5 · Code: allocation
Per-size indexes
The simplest allocator scans every spot and takes the first one that fits. Its cost grows with the size of the lot and is paid again on every entry, and the scan has to skip the same taken spots each time. We keep a per-size index instead: for each size, a set of the spot ids that are free right now. Finding a spot is then reading the first entry of a set.
export class Floor { readonly level: number; readonly #free = new Map<SpotSize, Set<string>>(); readonly #sizeOf = new Map<string, SpotSize>(); constructor(level: number, layout: Layout) { this.level = level; for (const size of SIZES) { const ids = new Set<string>(); for (let i = 1; i <= layout[size]; i++) { const id = `F${level}-${size[0]!.toUpperCase()}${i}`; ids.add(id); this.#sizeOf.set(id, size); } this.#free.set(size, ids); } }
The constructor builds ids such as F1-M1 and fills the index. A Set iterates in insertion order, like a Map, so values().next().value is the free spot of that size that was added earliest. The language defines that order, so it is the same on every engine: deleting F1-M1 and adding it back moves it behind F1-M2, and the next car gets the spot that has been free longest.
owns(spotId: string): boolean {
return this.#sizeOf.has(spotId);
}
peek(size: SpotSize): string | undefined {
return this.#free.get(size)?.values().next().value;
}
freeCount(size: SpotSize): number {
return this.#free.get(size)?.size ?? 0;
}
occupy(spotId: string): void {
const size = this.#sizeOf.get(spotId)!;
if (!this.#free.get(size)!.delete(spotId)) {
throw new ParkingError('SPOT_TAKEN', `${spotId} is taken`);
}
}
release(spotId: string): void {
this.#free.get(this.#sizeOf.get(spotId)!)!.add(spotId);
}Why a floor and not one big index in the lot? Each floor owns its spots and answers for them, so the rules about one level live in one class. The lot only decides the order in which floors are asked.
occupy is the guard for the invariant. Set.delete returns false when the id is not in the set, and that is exactly when the spot is already taken, so the floor throws SPOT_TAKEN. Without this check a second claim would pass silently.
The lot picks across floors
The lot wraps the floors and decides the order of preference. For each size the vehicle may use, smallest first, it asks each floor from the lowest. It returns the first hit.
export class ParkingLot { readonly #floors: readonly Floor[]; constructor(floors: readonly Floor[]) { this.#floors = floors; } // Smallest fitting size first, lowest floor first. Does not claim. peek(type: VehicleType): string | undefined { for (const size of FITS[type]) { for (const floor of this.#floors) { const id = floor.peek(size); if (id !== undefined) return id; } } return undefined; }
The choice is about the loop order. With sizes on the outside, a car prefers a medium spot on floor 3 over a large spot on floor 1. With floors on the outside it would take the nearest spot of any size and waste large ones. Choose the order that protects the scarce spots, and write the choice in a comment.
The rest of the class forwards occupy and release to the right floor, and builds the display board by adding up free counts.
occupy(spotId: string): void { this.#floorOf(spotId).occupy(spotId); } release(spotId: string): void { this.#floorOf(spotId).release(spotId); } // What the display board at the gate shows. board(): Record<SpotSize, number> { const out = { small: 0, medium: 0, large: 0 }; for (const size of SIZES) { for (const f of this.#floors) out[size] += f.freeCount(size); } return out; } #floorOf(spotId: string): Floor { const floor = this.#floors.find((f) => f.owns(spotId)); if (!floor) { throw new ParkingError('UNKNOWN_SPOT', spotId); } return floor; }
Tests for full floors and wrong sizes
Allocation is where the edge cases live, so it gets the most tests. Each one builds a tiny lot, because a lot of three spots is easier to reason about than a lot of three hundred.
The helper lotOf takes one [small, medium, large] count per floor and builds the lot, so lotOf([1, 1, 1]) is one floor with one spot of each size.
test('a bike takes the smallest spot first', () => { const lot = lotOf([1, 1, 1]); assert.equal(lot.peek('bike'), 'F1-S1'); }); test('a bike spills into a bigger spot when small is full', () => { const lot = lotOf([1, 1, 1]); lot.occupy('F1-S1'); assert.equal(lot.peek('bike'), 'F1-M1'); }); test('a car never gets a small spot', () => { const lot = lotOf([5, 0, 0]); assert.equal(lot.peek('car'), undefined); });
The rest of the tests cover a truck on a higher floor, a full floor and the guard.
test('a truck needs a large spot on any floor', () => { const lot = lotOf([1, 1, 0], [0, 0, 1]); assert.equal(lot.peek('truck'), 'F2-L1'); }); test('a full floor sends the car to the next one', () => { const lot = lotOf([0, 1, 0], [0, 1, 0]); lot.occupy('F1-M1'); assert.equal(lot.peek('car'), 'F2-M1'); }); test('occupying a taken spot throws SPOT_TAKEN', () => { const lot = lotOf([0, 1, 0]); lot.occupy('F1-M1'); assert.throws(() => lot.occupy('F1-M1'), { code: 'SPOT_TAKEN' }); });
✔ a bike takes the smallest spot first (1.5466ms) ✔ a bike spills into a bigger spot when small is full (0.3962ms) ✔ a car never gets a small spot (0.2267ms) ✔ a truck needs a large spot on any floor (0.2021ms) ✔ a full floor sends the car to the next one (0.2254ms) ✔ occupying a taken spot throws SPOT_TAKEN (0.988ms) ℹ tests 6 ℹ pass 6 ℹ fail 0
Output (durations vary)
Six tests pass. A bike spills into a larger spot only when the small ones are gone, a car is refused when only small spots exist, and a truck finds the one large spot even on a higher floor. The last test shows the guard: a second occupy of the same spot throws SPOT_TAKEN.
Each test name states a rule in plain words, so a failing run tells you which rule broke before you open the file. Small named cases also double as documentation for the next person who changes the loop order.
Part 6 · Code: fees and payment
A tariff strategy
The fee rule will change: new rates, a fee cap, weekend prices. Hard-coding it inside the service would mean editing the service each time. A strategy is an object that holds one swappable rule behind an interface. The service asks any Tariff for a fee, and which one it gets is decided when the lot is set up.
export interface Tariff { fee(type: VehicleType, minutes: number): Paise; } export class HourlyTariff implements Tariff { readonly #rate: Record<VehicleType, Paise>; readonly #graceMinutes: number; constructor(rate: Record<VehicleType, Paise>, graceMinutes: number) { this.#rate = rate; this.#graceMinutes = graceMinutes; } fee(type: VehicleType, minutes: number): Paise { if (minutes <= this.#graceMinutes) return 0; return Math.ceil(minutes / 60) * this.#rate[type]; } }
HourlyTariff takes the rate per vehicle type and the free minutes. A stay up to the free period costs nothing. Otherwise the fee is the number of started hours times the rate. Math.ceil(minutes / 60) is the rule for every charged stay: 15.001 minutes is already past the grace period and rounds up to one hour.
A second class can wrap the first. This is a decorator: it implements the same interface, holds another object of that type, and changes its answer.
export class CappedTariff implements Tariff { readonly #inner: Tariff; readonly #cap: Paise; constructor(inner: Tariff, cap: Paise) { this.#inner = inner; this.#cap = cap; } fee(type: VehicleType, minutes: number): Paise { return Math.min(this.#inner.fee(type, minutes), this.#cap); } }
CappedTariff leaves the hourly rule alone and caps the amount, so a fee cap is one new class and one changed line in the set-up code.
The lost-ticket fee is not part of the tariff on purpose. A lost ticket has no reliable entry time, so no stay length can be computed, and a flat amount is the honest answer. It lives in the set-up as lostFee, next to the tariff.
An injected clock
Fees depend on elapsed time, and real time makes tests slow and flaky. The fix is to treat the clock as a dependency. An injected clock is an object with a now() method that the service receives instead of calling Date.now() itself. Production passes the real clock, and tests pass a fake one that they control.
export class FakeClock implements Clock { #t: number; constructor(start = 0) { this.#t = start; } now(): number { return this.#t; } advanceMinutes(m: number): void { this.#t += m * 60_000; } }
FakeClock keeps a number and moves it only when the test says so. Advancing 61 minutes takes no time at all, and the elapsed time is exact. The service computes minutes as (now - issuedAt) / 60_000 when the driver pays.
reportLost(ticketId: string): void { this.get(ticketId).apply('lost'); } pay(ticketId: string): Paise { const t = this.get(ticketId); const minutes = (this.#d.clock.now() - t.issuedAt) / 60_000; const fee = t.state === 'lost' ? this.#d.lostFee : this.#d.tariff.fee(t.type, minutes); t.apply('pay'); t.recordPayment(fee); return fee; } exit(ticketId: string): void { const t = this.get(ticketId); t.apply('exit'); this.#d.lot.release(t.spotId); } get(ticketId: string): Ticket { const t = this.#tickets.get(ticketId); if (!t) throw new ParkingError('UNKNOWN_TICKET', ticketId); return t; }
Paying a lost ticket uses the flat fee instead of the tariff, and apply('pay') decides whether the move is legal. The fee is computed before the transition, and the transition throws before anything is recorded, so a rejected payment leaves the ticket as it was.
Tests across the hour edges
Edge cases for money are where bugs hide, so the tests sit exactly on the boundaries: 0 and 15 minutes are free, 15.001 minutes costs one hour, 60 minutes still costs one hour, and 60.001 minutes costs two.
test('fee at the edges of the grace period and each hour', () => { const t = new HourlyTariff(rates, 15); assert.equal(t.fee('car', 0), 0); assert.equal(t.fee('car', 15), 0); assert.equal(t.fee('car', 15.001), 2000); assert.equal(t.fee('car', 60), 2000); assert.equal(t.fee('car', 60.001), 4000); }); test('the service charges by the fake clock', () => { const { clock, svc } = setup(); const t = svc.park('DEMO-0001', 'car'); clock.advanceMinutes(61); assert.equal(svc.pay(t.id), 4000); assert.equal(t.state, 'paid'); }); test('a cap holds the fee down on a long stay', () => { const { clock, svc } = setup(10000); const t = svc.park('DEMO-0001', 'car'); clock.advanceMinutes(24 * 60); assert.equal(svc.pay(t.id), 10000); });
The helper setup builds a one-floor lot, a fake clock and a service, with an optional cap. The third test covers the decorator, and the other tests in the file cover the ticket rules: exit before payment, a lost ticket, a second exit and an unknown ticket.
✔ fee at the edges of the grace period and each hour (2.8684ms) ✔ the service charges by the fake clock (0.6581ms) ✔ a cap holds the fee down on a long stay (0.2032ms) ✔ exit before payment is NOT_PAID and keeps the spot (0.9157ms) ✔ a lost ticket pays the flat fee, then exits (0.241ms) ✔ a second exit is BAD_STATE, an unknown ticket is rejected (0.2273ms) ℹ tests 6 ℹ pass 6 ℹ fail 0
Output (durations vary)
All six pass. The unpaid exit test also checks that the board still shows no free medium spot, so a rejected exit really leaves the car parked. The lost-ticket test shows the full path: report lost, pay the flat fee, exit.
One more habit is worth keeping. Every fee in these tests is a whole number of paise, so assert.equal compares integers and there is no tolerance to argue about. The rupee sign appears only in the demo, where Intl.NumberFormat with the en-IN locale formats the amount for display. The same formatter prints 123456789 paise as ₹12,34,567.89, with the Indian digit grouping.
Every use case, tested
The use case lesson left six test.todo names. With the service, the tariff and the clock in place, each one can now become a real test that drives the whole lot the way its actor would. These are acceptance tests: they check a goal from the outside, through ParkingService, while the allocation and fee tests check single rules inside.
The helper openLot plays the admin. It builds two floors, an hourly tariff with a 15-minute free period, a ₹500 lost-ticket fee and a fake clock, so its first test is the admin's use case itself.
test('admin sets up floors and the tariff', () => { const { lot } = openLot(); assert.deepEqual(lot.board(), { small: 1, medium: 1, large: 1 }); }); test('driver parks a car and gets a ticket', () => { const { svc } = openLot(); const t = svc.park('DEMO-0001', 'car'); assert.equal(t.spotId, 'F1-M1'); assert.equal(t.state, 'active'); }); test('driver pays at exit and the spot is freed', () => { const { svc, lot, clock } = openLot(); const t = svc.park('DEMO-0001', 'car'); clock.advanceMinutes(130); assert.equal(svc.pay(t.id), 6000); svc.exit(t.id); assert.equal(lot.board().medium, 1); });
The driver's 130-minute stay is three started hours, so the fee is 6000 paise, and after exit the board counts the medium spot as free again. The other three use cases are the refusals and the lost ticket.
test('gate refuses entry when no spot fits', () => { const { svc } = openLot(); svc.park('DEMO-0001', 'truck'); const full = { code: 'LOT_FULL' }; assert.throws(() => svc.park('DEMO-0002', 'truck'), full); }); test('exit is refused for an unpaid ticket', () => { const { svc } = openLot(); const t = svc.park('DEMO-0001', 'bike'); assert.throws(() => svc.exit(t.id), { code: 'NOT_PAID' }); }); test('attendant marks a ticket lost, flat fee applies', () => { const { svc, clock } = openLot(); const t = svc.park('DEMO-0001', 'car'); clock.advanceMinutes(30); svc.reportLost(t.id); assert.equal(svc.pay(t.id), 50000); });
✔ admin sets up floors and the tariff (2.8498ms) ✔ driver parks a car and gets a ticket (0.3875ms) ✔ driver pays at exit and the spot is freed (0.3209ms) ✔ gate refuses entry when no spot fits (0.4952ms) ✔ exit is refused for an unpaid ticket (0.1794ms) ✔ attendant marks a ticket lost, flat fee applies (0.2135ms) ℹ tests 6 ℹ pass 6 ℹ fail 0 ℹ todo 0
Output (durations vary)
Six pass and no todo is left. Each name is the same sentence the use case lesson wrote, so the list of goals and the list of tests can be read side by side. If a requirement changes, the use case and its test change together.
Part 7 · Extensions and trade-offs
Two gates and the last spot
So far everything ran in one synchronous call, and JavaScript runs one synchronous call to completion before anything else starts. park peeks and occupies with no gap, so two gates cannot interleave inside it. The trouble starts when an await sits between the check and the claim.
Suppose each gate first checks the number plate against a block list, which is an asynchronous lookup. The gate peeks, awaits the camera, then claims. This is a race condition: the result depends on the order of events that nothing controls.
export class Gate { readonly #svc: ParkingService; readonly #lot: ParkingLot; readonly #verifier: Verifier; readonly #mutex: KeyedMutex; // Every gate of one lot must share one mutex. constructor(svc: ParkingService, lot: ParkingLot, verifier: Verifier, mutex: KeyedMutex) { this.#svc = svc; this.#lot = lot; this.#verifier = verifier; this.#mutex = mutex; } // Check, then await, then claim: another gate can slip in between. async parkUnsafe(plate: string, type: VehicleType): Promise<Ticket> { const spot = this.#lot.peek(type); if (spot === undefined) throw new ParkingError('LOT_FULL', type); await this.#verifier.check(plate); this.#lot.occupy(spot); return this.#svc.issue(plate, type, spot); }
Each Gate is one entry. All gates share the lot's service and lot, and each is handed a mutex as well.
Watch for both gates reading the same free spot before either one claims it
Read it as steps
Taking turns with a keyed mutex
There are two ways to fix it. The cheap one is to remove the await from between the check and the claim, for example by doing the camera check first and then calling the synchronous park.
When the gap cannot go away, make the gates take turns. A mutex (mutual exclusion lock) lets one task run at a time. In JavaScript a promise chain does the job. This small KeyedMutex keeps one chain per key, so work on the same key queues, while different keys do not wait for each other.
export class KeyedMutex { readonly #tails = new Map<string, Promise<void>>(); run<T>(key: string, fn: () => Promise<T>): Promise<T> { const prev = this.#tails.get(key) ?? Promise.resolve(); const result = prev.then(fn); const tail = result.then(() => {}, () => {}); this.#tails.set(key, tail); void tail.then(() => { if (this.#tails.get(key) === tail) this.#tails.delete(key); }); return result; } }
run appends fn to the end of the chain for the key. The stored tail swallows errors, so one task that rejects does not stop the ones queued behind it. parkSafe in Gate wraps the same steps in mutex.run('lot', ...).
// The same steps, one gate at a time. parkSafe(plate: string, type: VehicleType): Promise<Ticket> { return this.#mutex.run('lot', () => this.parkUnsafe(plate, type)); } }
The lock works only if every gate uses the same one. That is why the mutex is a constructor argument and not a field each gate creates for itself. The third line of the output above, own locks, is two gates that each made their own KeyedMutex: each lock queues only its own gate's calls, so the gates still interleave and gate B still gets SPOT_TAKEN. The last two lines share one mutex: with one spot the loser now gets LOT_FULL, and with two spots both cars park, on F1-M1 and F1-M2.
The key here is 'lot', a single lock for the whole lot. That serialises every entry, which is fine for a few gates. Splitting the lock by floor would need the gate to choose a floor before it holds the lock, so that is a redesign, not a one-line change. The mutex also protects only one process. Several servers would need a lock in shared storage, which is a different design.
EV chargers, caps and reservations
The model should absorb the "should" items without a rewrite. Take EV charging spots. We add 'ev' to the list of sizes and a vehicle type 'ev-car' that prefers an ev spot, then a medium, then a large. That is two union members and one row in the fit table. Because the tables are Record types, tsc lists every place that must now decide something. Here is the end state, in an extended copy of the project.
export const SIZES = ['small', 'medium', 'large', 'ev'] as const; export type SpotSize = (typeof SIZES)[number]; export type VehicleType = 'bike' | 'car' | 'truck' | 'ev-car'; export type Paise = number; // Sizes a vehicle may use, smallest first. export const FITS: Record<VehicleType, readonly SpotSize[]> = { bike: ['small', 'medium', 'large'], car: ['medium', 'large'], truck: ['large'], 'ev-car': ['ev', 'medium', 'large'], };
The two new names and the new fit row (in the extended copy)
To see the checklist, add only the two names to the original project, without the fit row, and type-check it.
npx tsc -p . | grep -o "^[a-z./-]*[.]ts" | sort | uniq -c1 allocation.test.ts 2 demo.ts 2 domain/lot.ts 1 domain/types.ts 3 fees.test.ts 2 race.test.ts 2 race.ts 3 usecases.test.ts
Output: errors per file after adding the two names
Sixteen errors in eight files, each one a place that listed the old sizes or vehicle types: the spot layouts in tests and the demo, the fee rates, the display board and the fit table itself. This is the useful kind of compile error, a checklist. Fixing them took four kinds of change: the new fit row, Layout made optional per size, an ev-car entry in each rate table, and an ev count of zero to start the board. Two tests then pin the behaviour.
test('an EV car takes a charger first, then a normal spot', () => { const lot = new ParkingLot([new Floor(1, { ev: 1, medium: 1 })]); assert.equal(lot.peek('ev-car'), 'F1-E1'); lot.occupy('F1-E1'); assert.equal(lot.peek('ev-car'), 'F1-M1'); }); test('an ordinary car never takes a charger', () => { const lot = new ParkingLot([new Floor(1, { ev: 2 })]); assert.equal(lot.peek('car'), undefined); });
✔ an EV car takes a charger first, then a normal spot (0.7431ms) ✔ an ordinary car never takes a charger (0.1357ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output (durations vary)
Where this design is weak
Every design has costs, and it helps to name them. The Set order means allocation is not by distance to the lift, only by age of vacancy. Tickets live in a Map inside the service, so a restart loses them; a real lot persists tickets through a repository. And the mutex is local to one process.
| Term | Meaning |
|---|---|
| Invariant | A condition that must always hold, such as a spot never being free and taken |
| Strategy | An object holding one swappable rule behind an interface |
| Injected clock | A time source passed in so tests control it |
| Race condition | A result that depends on the order of unsynchronised events |
| Mutex | A lock that lets one task at a time run a section |
Why did the invariant hold while the answer was still wrong in the two-gate run?
- Floor.occupy rejected the second claim, so no spot was given twice, but the check had gone stale during the await.
- Gate B got SPOT_TAKEN even when another spot was free.
Name two ways to fix the race and when each is right.
- Remove the await between check and claim: best when the slow step can move before the check.
- Serialise with a keyed mutex: when the await cannot be removed, within one process.
A teammate gives each Gate its own new KeyedMutex() inside the class. Two gates still hand out SPOT_TAKEN. Why?
- Each mutex queues only the calls made through its own gate, so calls from the two gates still interleave around the await.
All chapters · Previous: Solving a Design Problem: Requirements to Tested Code in Six Steps