Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 8
Module 4 · Design problems I: parking, elevators and libraries · Chapter 8 of 28
Elevator System: Cars, Hall Calls and Dispatching
Builds on Object-Oriented Design and UML: Use Case, Class, Sequence, Activity and State Diagrams, 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: Library Management: Catalogue, Copies, Loans, Holds and Fines.
Part 1 · Requirements
What the lifts must do
In a Gurugram office tower, hundreds of people press the same few buttons each morning and expect the right lift to arrive. This chapter models a bank of lifts as classes you can run, so you can see why the nearest car is often the wrong one.
A lift (or elevator) here is a car that travels along one shaft and serves a list of floors. A hall call is a request made on a floor, outside the car: it carries the floor and the direction the person wants to go. A car call is a request made inside the car: it carries only the destination floor. Everything else follows from these two kinds of request. The functional requirements for our twelve-floor building, numbered 0 to 11, are these.
- The building has several cars. Each car is in one place at a time and moves one floor per tick, where a tick is one simulated second.
- A hall call is given to exactly one car. A car call goes to the car it was pressed in.
- A car serves its stops in sweep order: it keeps going one way while stops remain that way, then reverses.
- When a car reaches a stop its doors open for two ticks and then close. A rider can hold the doors open.
- A car carries at most its capacity, eight people in our model. While it is overloaded the doors stay open.
- A technician can take a car out of service. The hall calls waiting for it go to the other cars.
- A request for a floor that does not exist is refused.
Most of these rules are answers to questions the short prompt "design an elevator system" leaves open. Ask the ones that change a class or a method first.
| Question | If the answer is yes | Our answer |
|---|---|---|
| Is there more than one car? | A dispatcher must choose a car per hall call |
Quality and scope
The non-functional requirements matter as much as the list above. The system should send the car that can really get there soonest, not just the closest on paper. It must never lose a call: a call given to a car is either served or reassigned. And it must be testable without waiting, so time is a tick counter that a test advances by hand.
| Must | Should | Out of scope |
|---|---|---|
| Hall and car calls, sweep order, doors, capacity, out of service | Peak-hour mode, destination dispatch (floor chosen before boarding) | Fire recall, express zones, motor and sensor control, weights in kilograms |
Sizes are made up for this chapter. Twelve floors, eight people and a two-tick door cycle are choices to keep the examples small, not figures from any real building.
A short example fixes the vocabulary. A rider on floor 4 presses the up button, which is a hall call for floor 4 going up. The dispatcher gives it to one car. When that car arrives and the rider steps in and presses 9, that is a car call, and the car adds floor 9 to its stops. Two requests, two different places, two different owners.
Notice what stays out. We do not model acceleration or the physical shaft. A car is an object that is at a floor and moves one floor per tick. That is enough to decide order, and order is the interesting part.
Check yourself
What is the difference between a hall call and a car call?
- A hall call is pressed on a floor and carries a direction; the dispatcher must pick a car for it.
- A car call is pressed inside a car and carries only a floor; it belongs to that car.
Why is time a tick counter in this model?
- A test can advance it by hand, so runs are exact and instant, and the same on every run.
The answer to "do riders choose the floor before boarding?" changes to yes. Which part of the model changes first?
- The request: a hall call would carry a destination as well as an origin, so the dispatcher can group riders going to nearby floors.
- Car calls from inside the car would mostly disappear, because the destination is already known.
Part 2 · Use cases
Actors and use cases
The actors are the rider and the technician. A use case is one goal an actor can reach. The rider calls a lift, chooses a floor and holds the doors. The technician takes a car out of service.
The diagram uses the same drawing as the parking lot chapter: actors are blue boxes, use cases are pills, and an arrow from a base case is labelled "includes" or "extended by".
"Call a lift" includes "choose a car", because every hall call needs a car chosen; the dispatcher does that, not the rider. "Reassign calls" extends "take out of service": it happens only when the car being removed still had hall calls waiting.
Notice that the dispatcher is not an actor. It is part of the system, a decision made on the rider's behalf. Keeping it off the actor list stops it from being modelled as a person who presses buttons.
Two more things could be actors in a larger system: the fire panel that recalls every car to a designated floor, and the building management system that reads car positions. We leave both out, because neither starts a use case in our first version. The rule for deciding is the one from the UML chapter: an actor is outside the boundary and has a goal that the system serves.
Flows and alternatives
Each use case gets a trigger, a main flow and alternatives.
| Use case | Main flow | Alternatives |
|---|---|---|
| Call a lift | Rider presses up or down; dispatcher chooses a car; car adds the floor as a stop | Floor outside the building: refused. No car in service: refused |
| Choose a floor | Rider presses a floor in the car; the car adds the stop | Same floor as the car: doors open |
| Hold the doors | Rider presses hold while doors are open; the countdown restarts | Doors closed: nothing happens |
| Take out of service | Car stops accepting calls and its hall calls are reassigned | No other car in service: refused, and the car keeps its calls |
Alternatives are where most of the bugs in a lift system live, so they are written down before any code. What if two riders press hall buttons on the same floor at once? Both calls are for the same floor and direction, and the stop list ignores a duplicate, so one stop serves them both. What if a rider presses the floor the car is already on? The doors open. What if a technician tries to take out the only working car? The request is refused before anything changes, so no waiting call is dropped.
Two choices are worth stating. A call for the floor a car is standing at, with doors closed or open, simply opens the doors. And an out-of-service car is never picked: it reports an infinite wait, so any car that can reach the floor beats it.
Use cases as test names
As in the parking lot chapter, each use case becomes a named test that exists before the code does. test.todo reports a name without running anything.
test.todo('rider calls a lift and a car is chosen'); test.todo('rider chooses a floor inside the car'); test.todo('rider holds the doors for a late passenger'); test.todo('technician takes a car out of service'); test.todo('a floor outside the building is refused');
✔ rider calls a lift and a car is chosen (0.874ms) # TODO ✔ rider chooses a floor inside the car (0.0815ms) # TODO ✔ rider holds the doors for a late passenger (0.0492ms) # TODO ✔ technician takes a car out of service (0.0495ms) # TODO ✔ a floor outside the building is refused (0.0563ms) # TODO ℹ tests 5 ℹ todo 5
Output (durations vary)
A test name like these has a useful property. It says what the system does in words a rider or a facilities manager could read, so the list works as a conversation with the person who asked for the system. Five todos, none failing. Later lessons replace them with tests that pass, and the use cases that carry the risk, choosing a car and reassigning calls, get several tests each.
Why is the dispatcher not an actor?
- It is part of the system. An actor is outside the system and starts a use case.
In the use case diagram, what does extend mean for "reassign calls"?
- It adds steps to taking a car out of service, and only when that car had hall calls waiting.
Part 3 · Class diagram
Finding the classes
Underline the nouns again: building, car, door, hall panel, car panel, dispatcher, request, floor. Each needs a decision.
| Noun | Decision | Why |
|---|---|---|
| Building | Class Building | Owns the cars and routes calls |
| Car | Class Car | Has a floor, a state and a list of stops |
| Door | State doors-open plus a counter on Car | Opens and closes only with the car |
| Hall panel, car panel | Methods hallCall and carCall | Buttons are inputs, not objects with rules |
| Dispatcher | Interface Dispatcher | The rule for choosing a car changes |
| Request | Value HallCall, a floor and a direction | No identity or behaviour |
| Stops | Class StopQueue | Two sorted lists with their own rules |
Floor is missing from the table on purpose. A floor here is a number from 0 to 11 with no state and no rules, so a class would only wrap an integer. The building checks the range in one place. If floors later gain state, such as a lit hall button that turns off when a car arrives, a Floor class or a map of lit buttons in Building would hold it.
The class diagram
floors: numberhallCall(floor, dir): carIdcarCall(carId, floor)tick()takeOutOfService(carId)id, capacityfloor, state, diraddStop(floor, dir?, hall?)tick(): event?eta(call): ticksup: floors ascendingdown: floors descendingahead(floor, dir)pick(floor, dir)floor: numberdir: up | downchoose(cars, call): Car?smallest floor gapsmallest eta- Building 1 → 1..* Car
- Car 1 → 1 StopQueue
- Building 1 → 1 Dispatcher (interface)
- Dispatcher (interface) 1 → * HallCall (value)
- NearestDispatcher → Dispatcher (interface)
- EtaDispatcher → Dispatcher (interface)
A building has one or more cars and one dispatcher. Each car owns one stop queue. The dispatcher interface takes the cars and a HallCall and returns a car, or nothing when no car is in service.
Two dispatchers fill the slot. NearestDispatcher is the rule most people write first: the smallest gap in floors. EtaDispatcher asks each car how many ticks it needs to open its doors for the call. We keep both, because the difference between them is the lesson of the dispatching code.
The skeleton in TypeScript
Direction, state, the request value and the error class come first. States and directions are string unions, because an enum is not erasable syntax and Node's type stripping rejects it.
export type Dir = 'up' | 'down'; export type CarState = | 'idle' | 'moving-up' | 'moving-down' | 'doors-open' | 'out-of-service'; export interface HallCall { floor: number; dir: Dir; } export type ElevatorCode = | 'BAD_FLOOR' | 'OUT_OF_SERVICE' | 'NO_CAR_AVAILABLE' | 'UNKNOWN_CAR'; export class ElevatorError extends Error { readonly code: ElevatorCode; constructor(code: ElevatorCode, message: string) { super(message); this.name = 'ElevatorError'; this.code = code; } }
The HallCall interface is a value: two calls with the same floor and direction are the same call, and nothing changes after creation. Because it is a plain object type, tests create calls with a literal and no class is needed. flip is a tiny helper that turns up into down and back, used wherever the code needs the opposite direction.
Every failure has a code from a closed set. The tests assert on the code, never on the message text.
npx tsc -p .
(no output, exit code 0)Output
Why is Door not a class here?
- Doors have no behaviour apart from the car: open for two ticks, then close. A state and a counter are enough.
Why does the car, not the dispatcher, own the eta calculation?
- Only the car knows its floor, direction and stops, so it is the one that can answer how soon it could arrive.
Part 4 · Car states and the dispatch sequence
States of one car
A state machine lists the states of an object and the events that move it between them. A car is idle, moving up, moving down, doors open or out of service. Doors open is a state of its own because the car refuses to move while they are open.
Watch for the car refusing to move while its doors are open
Read it as steps
A car moves only with its doors closed, and doors close before the next move.
The rejected event is the point. There is no arrow from doors-open to a moving state, so a move is refused. In the code nothing outside the car can order a move at all: each tick, a car with open doors only counts down. The only way out of doors-open is for the doors to close, which leaves the car idle. From idle, the next tick looks at the stops and starts moving, or stays where it is. The fault arrows say that a car can be taken out of service from any state, even between stops.
Calls, dispatch and the stop lists
When a rider presses a hall button, Building.hallCall checks the floor, asks the dispatcher for a car and gives that car the stop. The car puts the floor into one of two lists: stops to serve while going up, kept ascending, and stops to serve while going down, kept descending. A hall call joins the list of the direction the caller wants to go.
hallCall(floor: number, dir: Dir): string {
this.#checkFloor(floor);
const call = { floor, dir };
const car = this.#dispatcher.choose(this.#cars, call);
if (!car) throw new ElevatorError('NO_CAR_AVAILABLE', `${floor}`);
car.addStop(floor, dir, true);
const t = this.#time;
this.log.push(`t=${t} call ${floor} ${dir} -> car ${car.id}`);
return car.id;
}
carCall(carId: string, floor: number): void {
this.#checkFloor(floor);
this.#car(carId).addStop(floor);
}A car call has no direction, so the car works it out: a floor above the car goes in the up list and a floor below goes in the down list. A request for the car's own floor opens the doors at once.
The two lists carry the whole idea. While going up, the car stops at each floor in the up list. It reverses only when no stop of either kind remains above it. A down call above the car is the turning point: the car travels up to it, and picks up the passenger on the way back.
One hall call, start to finish
The driver for this chapter has two cars in the twelve-floor building: A on floor 0 and B on floor 5. A rider on floor 7 calls up. The car chosen then gets a car call for floor 9.
const a = new Car('A', 0, 8); const b = new Car('B', 5, 8); const building = new Building(12, [a, b], new EtaDispatcher()); building.hallCall(7, 'up'); while (b.state !== 'doors-open') building.tick(); building.carCall('B', 9); building.runUntilIdle(); for (const line of building.log) console.log(line); console.log(`B is at floor ${b.floor}, A is at floor ${a.floor}`);
t=0 call 7 up -> car B t=1 car B floor 6 t=2 car B doors open at 7 t=4 car B doors close t=5 car B floor 8 t=6 car B doors open at 9 t=8 car B doors close B is at floor 9, A is at floor 0
Output
Car B won, because it needed two ticks and A needed seven. B reached floor 7 at t=2, held its doors for two ticks, and closed them at t=4. The car call for 9 was pressed while the doors were open, and the car left at t=5, passing 8 and opening at 9 on t=6. Doors closed at t=8, and every car stopped. Car A never moved.
A driver script like this one is worth keeping after the real tests exist. It prints the story of a run in order, so a human can see at a glance that the numbers are plausible.
The log lines come from Building.tick. Each tick it asks every car what happened and writes a line only when something did, so a quiet tick leaves no line.
Why can a car not move while its doors are open?
- The state table has no transition from doors-open to a moving state; only doors closing leads out, to idle.
In the driver run, why does car B and not car A take the call from floor 7?
- B starts on floor 5 and needs two ticks to reach 7; A starts on floor 0 and needs seven.
Part 5 · Code: one car
Two sorted stop lists
The car's main job is order. The StopQueue keeps the up list ascending and the down list descending, so the next stop in the current direction is always at the front.
// Two sorted lists: floors to stop at while going up (ascending) and // while going down (descending). A hall call joins the list of the // direction the caller wants to travel. export class StopQueue { #up: number[] = []; #down: number[] = []; #hall = new Set<string>(); add(floor: number, dir: Dir, hall = false): void { const list = dir === 'up' ? this.#up : this.#down; if (!list.includes(floor)) { list.push(floor); list.sort(dir === 'up' ? (a, b) => a - b : (a, b) => b - a); } if (hall) this.#hall.add(`${floor}:${dir}`); } take(floor: number, dir: Dir): boolean { const list = dir === 'up' ? this.#up : this.#down; const at = list.indexOf(floor); if (at < 0) return false; list.splice(at, 1); this.#hall.delete(`${floor}:${dir}`); return true; }
A hall call and a car call for the same floor and direction share one stop. The car stops once, opens its doors once and serves both people.
Why two lists and not one list sorted by distance from the car? Nearest-first ignores direction. A rider who pressed up on floor 4 and chose 9 could be carried down to floor 2 first, because 2 is closer than 9, and the car can swing back and forth as presses arrive on both sides. With one list per direction the car finishes the leg it is on, and a press behind it joins the other list and waits for the way back. That keeps the promise the up and down buttons make, and a far stop can be delayed only by new stops ahead of the car, not by stops on both sides.
add ignores a floor that is already queued and re-sorts after each insert, which is fine for the dozens of stops a car holds. take removes a stop and also forgets that it came from a hall call, a detail the failover code needs later.
// Is any stop, in either list, beyond this floor in this direction? ahead(floor: number, dir: Dir): boolean { const hi = Math.max(this.#up.at(-1) ?? -Infinity, this.#down[0] ?? -Infinity); const lo = Math.min(this.#up[0] ?? Infinity, this.#down.at(-1) ?? Infinity); return dir === 'up' ? hi > floor : lo < floor; }
Serving one direction before reversing
The loop is in Car.#start and Car.#move. When idle, pick keeps the old direction if stops remain that way and reverses otherwise. A moving car advances one floor, then checks the floor it arrived at.
#start(): string | undefined { const dir = this.#stops.pick(this.#floor, this.#dir); if (!dir) return undefined; this.#dir = dir; this.#state = dir === 'up' ? 'moving-up' : 'moving-down'; return this.#move(); } #move(): string { this.#floor += this.#dir === 'up' ? 1 : -1; const d = this.#dir; if (this.#stops.take(this.#floor, d)) { this.#openDoors(); } else if (!this.#stops.ahead(this.#floor, d)) { // Last stop this way: serve a call waiting for the other way. const back = flip(d); if (this.#stops.take(this.#floor, back)) { this.#dir = back; this.#openDoors(); } else { this.#state = 'idle'; } } return this.#state === 'doors-open' ? `doors open at ${this.#floor}` : `floor ${this.#floor}`; }
The tick is the unit of time here. Nothing in Car reads a real clock, so a test that advances 200 ticks never waits, and the same ticks give the same log on every run.
Read #move closely. If the floor is in the list for the current direction, the car stops. If not, and nothing remains ahead, then this is the last stop this way, so the car takes any waiting call for the other direction here, reverses and opens its doors. Otherwise it keeps moving.
Watch for the stops being served by floor order, not by press order
Read it as steps
Tests for one car
The tests build a one-car building and read the floors where doors opened from the log. The helper one(floor, capacity) returns a car and its building, and opens pulls the floor numbers out of the log lines.
test('serves every stop going up, then reverses for the rest', () => { const { car, b } = one(5); [8, 3, 7].forEach((f) => b.carCall('A', f)); b.runUntilIdle(); assert.deepEqual(opens(b), [7, 8, 3]); assert.equal(car.floor, 3); }); test('a down call above the car is the turning point', () => { const { car, b } = one(3); b.hallCall(9, 'down'); b.carCall('A', 6); b.runUntilIdle(); assert.deepEqual(opens(b), [6, 9]); assert.equal(car.dir, 'down'); });
The first test is the sweep rule. The second is the turning point: a down call at floor 9 sends the car up past 6, which it serves first, and then 9 is where it reverses. The remaining tests cover the same-floor request, the overload rule, a bad floor and holding the doors.
test('a request for the current floor opens the doors', () => { const { car, b } = one(4); b.carCall('A', 4); assert.equal(car.state, 'doors-open'); }); test('an overloaded car keeps its doors open', () => { const { car, b } = one(4, 2); b.carCall('A', 4); car.setLoad(3); b.tick(); b.tick(); assert.equal(car.state, 'doors-open'); car.setLoad(2); b.runUntilIdle(); assert.equal(car.state, 'idle'); }); test('a floor outside the building is rejected', () => { const { b } = one(0); assert.throws(() => b.carCall('A', 12), { code: 'BAD_FLOOR' }); assert.throws(() => b.carCall('Z', 3), { code: 'UNKNOWN_CAR' }); });
✔ serves every stop going up, then reverses for the rest (1.6198ms) ✔ a down call above the car is the turning point (0.4397ms) ✔ a request for the current floor opens the doors (0.1425ms) ✔ an overloaded car keeps its doors open (0.1677ms) ✔ a floor outside the building is rejected (0.5576ms) ✔ holding the doors restarts the countdown (0.1013ms) ℹ tests 6 ℹ pass 6 ℹ fail 0
Output (durations vary)
Six pass. A failing run names the broken rule, which is faster than reading the loop. The overload test sets the load above capacity, ticks twice and checks that the doors are still open, then lowers the load and lets the car finish.
Why does the up list stay sorted ascending and the down list descending?
- The next stop in the direction of travel is then always the first entry, and the highest or lowest queued floor is at an end.
Part 6 · Code: dispatching
Why nearest is not enough
The simplest dispatcher picks the car with the smallest gap in floors. It reads well and it is often wrong, because direction matters more than distance.
export interface Dispatcher { choose(cars: readonly Car[], call: HallCall): Car | undefined; } // Picks the car with the smallest score; the first car wins ties. function best(cars: readonly Car[], score: (c: Car) => number) { let pick: Car | undefined; let low = Infinity; for (const car of cars) { const s = score(car); if (s < low) { low = s; pick = car; } } return pick; } // The tempting rule: the nearest car answers. export class NearestDispatcher implements Dispatcher { choose(cars: readonly Car[], call: HallCall): Car | undefined { const live = cars.filter((c) => c.state !== 'out-of-service'); return best(live, (c) => Math.abs(c.floor - call.floor)); } } // Asks each car how soon it could open its doors for this call. export class EtaDispatcher implements Dispatcher { choose(cars: readonly Car[], call: HallCall): Car | undefined { return best(cars, (c) => c.eta(call)); } }
best is a small helper that returns the car with the lowest score. The first car wins a tie, so the choice is deterministic. NearestDispatcher scores by the gap in floors. EtaDispatcher scores by car.eta(call), which copies the car, gives the copy the stop and ticks the copy until its doors open at that floor.
The Dispatcher interface has one method and no state, so a new rule is one new class. The building takes the dispatcher in its constructor, which means a test can build the same building with either rule and compare.
Asking the model costs more than a formula, and it can never disagree with the real car, because it is the real car's code. A formula for "going up, call behind me, call in the other direction" has many cases, and each one is a chance to drift from the movement rules.
A case where the nearest car loses
Car A is on floor 5 with a car call for 10. After one tick it is on floor 6, moving up. Car B is idle on floor 2. A rider on floor 5 presses up.
const a = new Car('A', 5, 8); const b = new Car('B', 2, 8); const building = new Building(12, [a, b], new EtaDispatcher()); building.carCall('A', 10); building.tick(); const call = { floor: 5, dir: 'up' } as const; const gap = (c: Car) => Math.abs(c.floor - call.floor); const who = (d: Dispatcher) => d.choose([a, b], call)?.id; console.log(`A: floor ${a.floor}, ${a.state}`); console.log(`B: floor ${b.floor}, ${b.state}`); console.log(`floors away: A ${gap(a)}, B ${gap(b)}`); console.log(`ticks to open: A ${a.eta(call)}, B ${b.eta(call)}`); console.log(`nearest picks ${who(new NearestDispatcher())}`); console.log(`eta picks ${who(new EtaDispatcher())}`);
A: floor 6, moving-up B: floor 2, idle floors away: A 1, B 3 ticks to open: A 11, B 3 nearest picks A eta picks B
Output
A is one floor away but has just passed the call. It must reach 10, open its doors, come back down and only then stop at 5, which takes 11 ticks in total: four for the climb, two for the doors and five for the way back down. B is three floors away and idle, so it opens at 5 on tick three. The nearest rule picks A and the ETA rule picks B.
Watch for the dispatcher ignoring the car that is only one floor away
Read it as steps
Car A is one floor away but heading up; car B is three floors away and idle.
Tests that pin the choice
Each test builds the same two cars. The first checks both dispatchers on the call from the scene. The second checks that a car already heading the right way wins, and the third that a car out of service is never chosen.
test('the nearest car is wrong for a call it just passed', () => { const { a, b } = cars(); const call = { floor: 5, dir: 'up' } as const; assert.equal(a.floor, 6); assert.equal(new NearestDispatcher().choose([a, b], call), a); assert.equal(new EtaDispatcher().choose([a, b], call), b); }); test('a car already heading the right way wins', () => { const { a, b } = cars(); const call = { floor: 8, dir: 'up' } as const; assert.equal(new EtaDispatcher().choose([a, b], call), a); }); test('out of service cars are never chosen', () => { const { a, b } = cars(); b.takeOutOfService(); const call = { floor: 2, dir: 'up' } as const; assert.equal(new EtaDispatcher().choose([a, b], call), a); assert.equal(new NearestDispatcher().choose([b], call), undefined); });
✔ the nearest car is wrong for a call it just passed (0.9366ms) ✔ a car already heading the right way wins (0.1416ms) ✔ out of service cars are never chosen (0.174ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output (durations vary)
A good dispatch test builds the situation by moving real cars, as cars() does, instead of setting private fields. That way the test keeps working if the internals of Car change, as long as its behaviour does not.
The test that matters most is the first, because it fails on the nearest rule and passes on the ETA rule. If someone later simplifies the dispatcher back to the gap in floors, that test is the one that goes red.
Every use case, tested
The use case lesson left five test.todo names. With cars, the building and a dispatcher in place, each becomes an acceptance test: it reaches the goal through Building, the way a rider or technician would, instead of testing one class alone. The helper tower builds two idle cars in the twelve-floor building, A at the lobby and B on floor 8.
test('rider calls a lift and a car is chosen', () => { const { building } = tower(); assert.equal(building.hallCall(6, 'down'), 'B'); building.runUntilIdle(); assert.match(building.log.join('\n'), /car B doors open at 6/); }); test('rider chooses a floor inside the car', () => { const { a, building } = tower(); building.carCall('A', 4); building.runUntilIdle(); assert.equal(a.floor, 4); }); test('rider holds the doors for a late passenger', () => { const { a, building } = tower(); building.carCall('A', 0); building.tick(); a.holdDoors(); building.tick(); assert.equal(a.state, 'doors-open'); });
A down call from floor 6 goes to B, which is two floors away with nothing else to do, and the log shows its doors opening at 6. Holding the doors one tick after they open keeps them open on the tick when they would have closed.
test('technician takes a car out of service', () => { const { a, b, building } = tower(); building.hallCall(10, 'down'); building.takeOutOfService('B'); assert.equal(b.state, 'out-of-service'); building.runUntilIdle(); assert.equal(a.floor, 10); }); test('a floor outside the building is refused', () => { const { building } = tower(); const bad = { code: 'BAD_FLOOR' }; assert.throws(() => building.hallCall(12, 'up'), bad); assert.throws(() => building.carCall('A', -1), bad); });
✔ rider calls a lift and a car is chosen (1.551ms) ✔ rider chooses a floor inside the car (0.234ms) ✔ rider holds the doors for a late passenger (0.171ms) ✔ technician takes a car out of service (1.1371ms) ✔ a floor outside the building is refused (0.7366ms) ℹ tests 5 ℹ pass 5 ℹ fail 0 ℹ todo 0
Output (durations vary)
Five pass and no todo is left. The technician's test is the failover rule seen from outside: B had the call for floor 10, B went out of service, and A answered instead.
What does the ETA dispatcher ask each car?
- How many ticks until the car could have its doors open at the call floor, simulated on a copy of the car.
Part 7 · Extensions and trade-offs
A car fails mid-trip
A car can be taken out of service while it has calls waiting. Its hall calls must not vanish. The stop queue remembers which stops came from a hall call, so takeOutOfService returns them, clears the queue and marks the car. The building then sends each returned call back through the dispatcher.
takeOutOfService(): HallCall[] {
const pending = this.#stops.hallCalls();
this.#stops = new StopQueue();
this.#state = 'out-of-service';
return pending;
}Calls pressed inside the car are dropped, because in our model the passengers get out at the floor where the car stopped. Hall calls are different: someone is still waiting on a floor, and they must be answered.
The building decides whether the car may go at all. It checks for another car in service before it touches anything, so a refused request leaves the car, its stops and its calls exactly as they were.
takeOutOfService(carId: string): void { const car = this.#car(carId); const live = (c: Car) => c !== car && c.state !== 'out-of-service'; if (!this.#cars.some(live)) { throw new ElevatorError('NO_CAR_AVAILABLE', `only ${carId} left`); } const pending = car.takeOutOfService(); this.log.push(`t=${this.#time} car ${carId} out of service`); for (const call of pending) this.hallCall(call.floor, call.dir); }
test('calls of a failed car move to the other car', () => { const a = new Car('A', 0, 8); const b = new Car('B', 11, 8); const building = new Building(12, [a, b], new EtaDispatcher()); assert.equal(building.hallCall(3, 'up'), 'A'); building.tick(); building.takeOutOfService('A'); building.runUntilIdle(); assert.equal(a.state, 'out-of-service'); assert.equal(b.floor, 3); assert.throws(() => a.addStop(5), { code: 'OUT_OF_SERVICE' }); }); test('the last car in service cannot be taken out', () => { const a = new Car('A', 0, 8); const building = new Building(12, [a], new EtaDispatcher()); building.hallCall(3, 'up'); assert.throws(() => building.takeOutOfService('A'), { code: 'NO_CAR_AVAILABLE', }); building.runUntilIdle(); assert.equal(a.floor, 3); });
✔ calls of a failed car move to the other car (2.3391ms) ✔ the last car in service cannot be taken out (0.2598ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output (durations vary)
In the first test car A is given a call for floor 3 and starts moving. It is taken out of service after one tick, on floor 1 on its way up. The dispatcher gives the call to B, which was on floor 11, and B ends on floor 3. Adding a stop to A now throws OUT_OF_SERVICE. In the second test A is the only car, so the request is refused, A stays in service and still answers the call at floor 3.
Peak hours and destination dispatch
Two extensions are worth sketching, though we do not build them. In the up-peak period of a working morning most riders start in the lobby and go up, so one useful rule is to send idle cars back to the lobby instead of leaving them where they stopped. That is a rule about idle cars, so it belongs to the dispatcher or a small scheduler, not to the sweep.
In destination dispatch riders key in their floor on a panel at the landing, before boarding, and the system tells them which car to take. The request then carries both an origin and a destination, which is a change to HallCall and the dispatcher interface. The car's sweep logic, and the StopQueue underneath it, stay the same.
Because the dispatcher is behind an interface, both extensions replace one object, and the existing tests of the car keep passing.
Where this design is weak
The sweep rule is simple and has costs. A steady stream of new stops ahead of a car can keep it going one way while someone waits behind it. A second version of this code would bound the wait, for example by giving a call that has waited too long to another car.
The ETA is also a prediction. It assumes no new calls arrive before the car gets there, and each new call can change the answer. The dispatcher also decides once per hall call and never revisits it, so a car that becomes free a moment later cannot take the call over. Both are acceptable for a first version; re-scoring waiting calls on every tick is a natural next step, and it reuses eta unchanged.
The simulation costs one small copy and up to a few hundred ticks per car per call. For a dozen cars that is cheap; for a very large bank, a formula or a cache would be worth the added cases.
| Term | Meaning |
|---|---|
| Hall call | A request made on a floor, with a direction |
| Car call | A request made inside a car, with a destination floor |
| Tick | One simulated second in the model |
| Sweep | Serving stops in one direction before reversing |
| ETA | Ticks until a car could open its doors for a call |
What happens to a car's hall calls when it is taken out of service?
- They are returned to the building and sent through the dispatcher again.
- Calls pressed inside the car are dropped; the passengers leave at the current floor.
Why do up-peak mode and destination dispatch not require a new Car?
All chapters · Previous: Parking Lot: Floors, Spots, Tickets and Fees