Skip to content

Instantly share code, notes, and snippets.

@kevinmorio
Created September 11, 2015 19:55
Show Gist options
  • Save kevinmorio/d5cb947f5ebb0913aa3c to your computer and use it in GitHub Desktop.
Save kevinmorio/d5cb947f5ebb0913aa3c to your computer and use it in GitHub Desktop.
Graph implementation
var Graph = function() {
this.verticesMap = new Map();
this.edgesCount = 0;
};
Graph.prototype.getNumVertices = function() {
return this.verticesMap.size;
}
Graph.prototype.getNumEdges = function() {
return this.edgesCount;
}
Graph.prototype.validateVertex = function(v) {
if (!this.hasVertex(v)) {
throw new Error("Illegal Vertex :" + v + " is not a vertex");
}
}
Graph.prototype.degree = function(v) {
this.validateVertex(v);
return this.verticesMap.get(v).length;
}
Graph.prototype.addEdge = function(v, w) {
if (!this.hasVertex(v)) this.addVertex(v);
if (!this.hasVertex(w)) this.addVertex(w);
if (!this.hasEdge(v, w)) this.edgesCount++;
this.verticesMap.get(v).add(w);
this.verticesMap.get(w).add(v);
}
Graph.prototype.addVertex = function(v) {
if (!this.hasVertex(v)) this.verticesMap.set(v, new Set());
}
Graph.prototype.hasEdge = function(v, w) {
this.validateVertex(v);
this.validateVertex(w);
return this.verticesMap.get(v).has(w);
}
Graph.prototype.hasVertex = function(v) {
return this.verticesMap.has(v);
}
Graph.prototype.toString = function() {
string = "";
for (var v in this.verticesMap.keys()) {
string += v.toString() + ": ";
for (let w of this.verticesMap.get(v).values()) {
string += w.toString() + " ";
}
string += "\n";
}
return string;
}
var graph = new Graph();
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("C", "D");
graph.addEdge("D", "E");
graph.addEdge("D", "G");
graph.addEdge("E", "G");
graph.addVertex("H");
console.log(graph);
console.log("Vertices: " + graph.getNumVertices());
console.log("Edges: " + graph.getNumEdges());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment