Home > front end >  I need help to understand this function
I need help to understand this function

Time:08-18

This code from (Eloquent Javascript chapter 7 3rd edition).

A mail-delivery robot picking up and dropping off parcels. The village consists of 11 places with 14 roads between them. It can be described with this array of roads.

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",
];

// Okay I was trying to understand this function below but I couldn't, specially the for loop

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

What does the for loop do?

CodePudding user response:

edges.map() calls a function on each element of the edges array (which corresponds to the global roads array because it's the argument to the function). It collects all the return values into an array and returns this.

The function it calls uses .split('-') to split each string into an array, using - as the delimiter. For example, the string "Alice's House-Bob's House" becomes ["Alice's House", "Bob's House"]. So together with .map(), this returns an array of nested arrays:

[
    ["Alice's House", "Bob's House"],
    ["Alice's House", "Cabin"],
    ...
]

The for-of loop then iterates over the elements of this array. Using the destructuring pattern [from, to] as the iteration variable assigns the variables from and to from the corresponding elements of each nested array. So on the first iteration from = "Alice's House" and to = "Bob's House". On the second iteration from = "Alice's House" and to = "Cabin".

The loop body then calls addEdge() with these variables to create graph edges that connect the two nodes in each direction.

  • Related