Skip to content

Instantly share code, notes, and snippets.

@sibnerian
Forked from saradornblaser/roadmap.js
Created August 26, 2018 15:53
Show Gist options
  • Save sibnerian/eb6fb73040d3fcb3b5dd66c8684fc615 to your computer and use it in GitHub Desktop.
Save sibnerian/eb6fb73040d3fcb3b5dd66c8684fc615 to your computer and use it in GitHub Desktop.
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