How does this snippet in Eloquent Javascript work?

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 Likes

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

2 Likes

Thank you so much! :grinning:

1 Like