With the stops numbered, the report turns to what happened at them. Its first late departure is the N3 that left Central Station at 23:40, eleven minutes late, with Amira driving. The team wants to know where the timetable’s slack let her catch up. The Python script finds out with a while loop that ports almost unchanged. Along the way, you’ll encounter one trap and one loop Python doesn’t have.
Loop Until the Bus Catches Up
Here’s how Python’s loop syntax maps onto JavaScript, plus the one loop Python lacks:
| Python | JavaScript |
|---|---|
while late > 0: |
while (late > 0) { ... } |
while True: |
while (true) { ... } |
break, continue |
break;, continue; |
| no equivalent | do { ... } while (condition); |
The condition goes in parentheses and the body in braces because JavaScript doesn’t read indentation. Watch out for the capital T when you port while True:. JavaScript writes lowercase true and false, and null stands in for None. Here’s the Python script’s catch-up loop in JavaScript, printing the delay after each stop until N3 catches up or runs out of stops:
const stops = [
{ name: "Market Square", slack: 3 },
{ name: "Elm Street", slack: 0 },
{ name: "Riverside", slack: 4 },
{ name: "Hospital", slack: 4 },
{ name: "Northgate", slack: 2 },
];
let late = 11;
let stopIndex = 0;
while (late > 0 && stopIndex < stops.length) {
late -= stops[stopIndex].slack;
console.log(`${stops[stopIndex].name}: ${late} min late`);
stopIndex++;
}
Run it, and the delay shrinks at every stop except Elm Street:
Market Square: 8 min late
Elm Street: 8 min late
Riverside: 4 min late
Hospital: 0 min late