In the last exercise, you made the check-in desk’s booking lookup safe for every passenger who walks up. That was the final new piece. You can now name shapes, pin values down with literal types, narrow a union, give each state its own member, make a switch handle every case, and deal with values that might be missing.
In this project, you’ll put those pieces together on Harbor Line’s crossings and tickets, the code that started the course. You’ll model them so that each state requires its own data and code can read that data only after checking the state. Then you’ll build the departures board, the ticket desk’s rules, and the fares on top of that model. Start with the code you’re replacing and the bug that made the owners ask for a rewrite.
Start From the Old Crossings and Tickets
A rewrite needs a reason, and Harbor Line’s is a morning when the departures board told passengers to board a crossing that wasn’t going anywhere. Here’s that crossing as the old JavaScript stored it, cut down from its dozen optional properties to the ones that matter:
old-crossing.js
export const hl1120 = {
id: "HL-1120",
boat: "Puffin",
to: "Heron Key",
departs: "11:20",
status: "cancelled",
reason: "gale warning",
gate: "B",
};
The crew called boarding at gate B, so the record got a gate. Then a gale warning came in, and the code that canceled the crossing changed status and added a reason, but it never removed the gate. Here’s the old function that writes the crossing’s line on the board:
old-board.js
import { hl1120 } from "./old-crossing.js";
function boardLine(crossing) {
const start = `${crossing.departs} ${crossing.boat} to ${crossing.to}`;
if (crossing.gate) {
return `${start}: boarding at gate ${crossing.gate}`;
}
if (crossing.status === "cancelled") {
return `${start}: canceled (${crossing.reason})`;
}
return `${start}: on time`;
}
console.log(boardLine(hl1120));
You don’t need to type these files in. Here’s what the board showed that morning, as Node.js prints it:
$ node old-board.js
11:20 Puffin to Heron Key: boarding at gate B