Created
March 20, 2018 12:26
-
-
Save jonurry/540b247388c5923ad0ee41a7dd805ac5 to your computer and use it in GitHub Desktop.
10.2 Roads Module (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("-"))); |
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
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 functionbuildGraph
that is used to build the graph. This function expects an array of two-element arrays (the start and end points of the roads).