I am stuck (again:sweat:) in the chapter 7 of Eloquent Javascript. At the beginning of the project, we are supposed to convert a list of roads (recorded in an array of strings) into a data structure. The author directly gave the solution, but I have no idea how the function work. Can anyone help give an explanation on it? Many Thanks!
The list of roads and its corresponding array:
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"
];
The array of strings isnāt very easy to work with. What weāre interested in is the destinations that we can reach from a given place. Letās convert the list of roads to a data structure that, for each place, tells us what can be reached from there.
This is the function that converts the list into a data structure:
function buildGraph(edges) {
let graph = Object.create(null);
// How does this addEdge function work at all?
function addEdge(from, to) {
if (graph[from] == null) {
graph[from] = [to]; //Why assign graph[from] to [to] instead of to?
} else {
graph[from].push(to);
}
}
for (let [from, to] of edges.map(r => r.split("-"))) {
addEdge(from, to);
addEdge(to, from);
}
return graph;
}
const roadGraph = buildGraph(roads);