Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created March 20, 2018 12:26
Show Gist options
  • Save jonurry/540b247388c5923ad0ee41a7dd805ac5 to your computer and use it in GitHub Desktop.
Save jonurry/540b247388c5923ad0ee41a7dd805ac5 to your computer and use it in GitHub Desktop.
10.2 Roads Module (Eloquent JavaScript Solutions)
const {buildGraph} = require("./graph");
const roads = [
"Alice's House-Bob's House", "Alice's House-Cabin",
"Alice's House-Post Office", "Bob's House-Town Hall",
"Daria's House-Ernie's House", "Daria's House-Town Hall",
"Ernie's House-Grete's House", "Grete's House-Farm",
"Grete's House-Shop", "Marketplace-Farm",
"Marketplace-Post Office", "Marketplace-Shop",
"Marketplace-Town Hall", "Shop-Town Hall"
];
function splitRoads(r) {
let newRoads = [];
for (let roadPair of r) {
newRoads.push(roadPair.split('-'));
}
return newRoads;
}
exports.roadGraph = buildGraph(splitRoads(roads));
// a better solution is to use a map:
// exports.roadGraph = buildGraph(roads.map(r => r.split("-")));
@jonurry
Copy link
Author

jonurry commented Mar 20, 2018

Modules

10.2 Road Module

Write a CommonJS module, based on the example from Chapter 7, which contains the array of roads and exports the graph data structure representing them as roadGraph. It should depend on a module ./graph, which exports a function buildGraph that is used to build the graph. This function expects an array of two-element arrays (the start and end points of the roads).

@jonurry
Copy link
Author

jonurry commented Mar 20, 2018

Hints

Since this is a CommonJS module, you have to use require to import the graph module. That was described as exporting a buildGraph function, which you can pick out of its interface object with a destructuring const declaration.

To export roadGraph, you add a property to the exports object. Because buildGraph takes a data structure that doesn’t precisely match roads, the splitting of the road strings must happen in your module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment