How does this snippet in Eloquent Javascript work?

How does this snippet in Eloquent Javascript work?
0.0 0

#1

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);

#2

if graph[from] is null then there is no array to push to. You have to create that array for first use.
graph[from].push(to) won’t work if there is nothing to push on to.

Takes string like ‘Alice’s House - Bob’s House’
Creates two variables so that
from = ‘Alices House’;
to = ‘Bob’s House’;
addEdge is called twice because if there is a route from Alice’s to Bob’s there is also a route from Bob’s to Alice’s


#3

Thank you so much! :grinning: