Porting the Dock Report
In this project, you ported the crew’s dock report to JavaScript, ran it, and got the same five dock lines Python prints. The van’s lines go in the loop’s gaps in the exercise.
- The list of dicts becomes an array of objects: the brackets and braces stay, and the keys
lose their quotes. Each name gets a
const, and the closed list is an array too. - The fill rate is one line of arithmetic, so it becomes an arrow in a
const. The arrow returns its formula without areturn. classify()is a named building block, so it stays a function declaration, with braces around its body. Eachelifturns intoelse if, and each==into===. A lookup with a fixed key becomes a dot, sodock["bikes"]becomesdock.bikes.- In the closed check, Python’s
inbecomesclosedDocks.includes(dock.name): the list first, then the value. JavaScript’sinasks about keys, which in an array are its positions, never its values. Within, Market Hall would count as empty, and the van would load bikes it shouldn’t. - The loop goes through the array with
for...of, with aconstfor each dock, andstatusandfillget aconsttoo, since each pass has its own. - The print line becomes a template literal. The format spec can’t come along, because a hole
holds an expression, not a format spec, so you round inside the hole with
fill.toFixed(0).
Here’s the port, dock-report.js, with the van’s lines still to come:
const docks = [
{ name: "Elm Street", bikes: 0, slots: 12 },
{ name: "Harbor Square", bikes: 14, slots: 1 },
{ name: "Station Road", bikes: 6, slots: 8 },
{ name: "Market Hall", bikes: 0, slots: 10 },
{ name: "Riverside Park", bikes: 11, slots: 2 },
];
const closedDocks = ["Market Hall"];
const fillRate = (bikes, slots) => bikes / (bikes + slots) * 100;
function classify(dock) {
if (closedDocks.includes(dock.name)) {
return "closed";
} else if (dock.bikes === 0) {
return "empty";
} else if (dock.slots <= 2) {
return "nearly full";
} else {
return "ok";
}
}
for (const dock of docks) {
const status = classify(dock);
const fill = fillRate(dock.bikes, dock.slots);
console.log(`${dock.name}: ${status}, ${fill.toFixed(0)}%`);
}