Porting the Night-Bus Report
In this project, you ported the night-bus report’s first three sections from Python to JavaScript, and left the supervisors for the exercise.
- The data carries over with property names unquoted and lowercase
falseandtrue. The lists becomeconstarrays. The routes are listed busiest first, by riders. - Every loop header declares its variable:
for (const trip of trips). Python’s loop creates the name for you, but JavaScript’s doesn’t. Leave theconstout, and the module stops withReferenceError: trip is not defined, because ES modules run in strict mode. .append()becomes.push(), andenumerate(late, start=1)becomeslate.entries(), withindex + 1where a person reads the number.- Objects have no
fromkeys(), so a short loop starts each route at0. Python’s.items()becomesObject.entries(), destructured in the header. Route names keep their order in an object; number-like keys, such as hours, come out sorted, and aMapkeeps them in order. - JavaScript loops have no
else. Ported with} else {after the loop, the file stops withSyntaxError: Unexpected token 'else'. JavaScript checks the whole file before it runs any of it, so even the sections above the loop don’t print. A loop that only searches becomes.find(), which returnsundefinedwhen nothing matches, so an ordinaryif...elsetakes over.
Here are the report’s sections in JavaScript, as you left them. They read last night’s trips,
which the full file at the end of this page lists:
const routes = ["N3", "N7", "N26"]; // busiest first
const supervisors = ["Priya", "Joel", "Marta"];
// Late departures, numbered for the morning call
const late = [];
for (const trip of trips) {
if (trip.delay > 0) {
const where = `${trip.route} left ${trip.stop}`;
late.push(`${where} ${trip.delay} min late`);
}
}
for (const [index, line] of late.entries()) {
console.log(`${index + 1}. ${line}`);
}
// Delay totals per route
const totals = {};
for (const route of routes) {
totals[route] = 0;
}
for (const trip of trips) {
totals[trip.route] += trip.delay;
}
for (const [route, total] of Object.entries(totals)) {
console.log(`${route}: ${total} min late in total`);
}
// The first canceled trip on the busiest route
const busiest = routes[0];
const first = trips.find(
(trip) => trip.route === busiest && trip.canceled,
);
if (first !== undefined) {
console.log(`Canceled on ${busiest}: ${first.departs}`);
} else {
console.log(`No canceled trips on ${busiest}`);
}
// Each route's supervisor: your turn in the exercise