Mazhar Ali
Mazhar Ali

Reputation: 366

Can someone help me understand this code?

Here's the full project

I don't understand how the graph[from] works, is it checking the value like in array at 'from' location? Or is 'from' a property name of the object? I tried both in my terminal, using from as property name works when it is a number. Using it as an array index gives me an error that 'from is undefined'. Also the graph[from].push(to). How it works?

function buildGraph(edges) {
  let graph = Object.create(null);

  function addEdge(from, to) {
    if (graph[from] == null) {
      graph[from] = [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);

Upvotes: -1

Views: 112

Answers (2)

Jean-Philippe Bergeron
Jean-Philippe Bergeron

Reputation: 373

Hit your favorite browser's dev tools. Type this in it :

let roadsX = [
  "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 buildGraph(edges) {
  let graph = Object.create(null);
  function addEdge(from, to) {
    if (graph[from] == null) {
      graph[from] = [to];
    } else {
      graph[from].push(to);
    }
  }
  for (let [from, to] of edges.map(r => r.split("-"))) {
    addEdge(from, to);
    addEdge(to, from);
  }
  return graph;
}

let roadGraphX = buildGraph(roads);

console.log(roadGraphX);

You'll see what the function does.

Upvotes: -1

Beri
Beri

Reputation: 11620

You have a list of roads, that are defined as list os String pairs, joined by '-', like "Alice's House-Bob's House" is a road connecting Alice and Bob house.

Each road is then combined of 2 edges: Alice House and Bob house (you split road to edge with split('_')).

Now you create a map of roads, here it's called graph. For each road you add 2 edged, from point A-> B and B-> A.

addEdge(from, to);
addEdge(to, from);

Because you can use same road to travel in both directions.

Each addEdge call checks if there is a edge from registered already in the graph. But in my opinion it should look like this:

 function addEdge(from, to) {
    if (!graph[from]) { // if object 'from' is not yet register, add an empty array to from key
      graph[from] = [];
    }
    graph[from].push(to); // add edge 'to, to mapping of 'from'
  }

so in the end you will build a map, that would look like this:

graph = {
   'Alice house': ['Bob house', 'Post office'],
   'Post office': ['Alice house'],
   'Bob house': ['Alice house']
}

Upvotes: 0

Related Questions