Hello, everyone. I’m working through Eloquent JavaScript and I got really, really stuck on a problem so I gave in and looked at the answer but there’s something in the answer I don’t understand.
First, the answer:
function lazyRobot({place, parcels}, route) {
if (route.length == 0) {
// Describe a route for every parcel
let routes = parcels.map(parcel => {
if (parcel.place != place) {
return {route: findRoute(roadGraph, place, parcel.place),
pickUp: true};
} else {
return {route: findRoute(roadGraph, place, parcel.address),
pickUp: false};
}
});
// This determines the precedence a route gets when choosing.
// Route length counts negatively, routes that pick up a package
// get a small bonus.
function score({route, pickUp}) {
return (pickUp ? 0.5 : 0) - route.length;
}
route = routes.reduce((a, b) => score(a) > score(b) ? a : b).route;
}
return {direction: route[0], memory: route.slice(1)};
}
runRobotAnimation(VillageState.random(), lazyRobot, []);
The part I don’t understand is .route after the end of the reduce function. Can anyone help me figure out what this does? Thank you!
Edit: Here’s the findRoute function for reference
function findRoute(graph, from, to) {
let work = [{at: from, route: []}];
for (let i = 0; i < work.length; i++) {
let {at, route} = work[i];
for (let place of graph[at]) {
if (place == to) return route.concat(place);
if (!work.some(w => w.at == place)) {
work.push({at: place, route: route.concat(place)});
}
}
}
}