Last active
August 26, 2018 15:53
-
-
Save saradornblaser/cb2f8efa32a61901e062ec8ea69fa2cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildGraph(edges) { | |
let graph = Object.create(null); | |
function addEdge(from, to) { | |
if (graph[from] == null) { | |
graph[from] = [to]; | |
} else { | |
graph[from].push(to); | |
} | |
console.log(from, to); | |
console.log(graph[from]); //vs console.log(graph); why does printing the entire graph here print the completed graph on the second call, even though it shouldn't be fully constructed until the last call? | |
} | |
for (let [from, to] of edges.map(r => r.split("-"))) { | |
addEdge(from, to); | |
addEdge(to, from); | |
} | |
return graph; | |
} | |
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" | |
]; | |
const roadGraph = buildGraph(roads); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment