Last active
December 29, 2015 18:09
-
-
Save shamasis/7708683 to your computer and use it in GitHub Desktop.
Directed graph data structure
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
var Graph = function () { | |
this.vertices = {}; | |
this.edges = []; | |
this.length = 0; | |
}; | |
Graph.Vertex = function (name, value) { | |
this.name = name; | |
this.edges = []; | |
this.value = value; | |
}; | |
Graph.Vertex.prototype.degree = function () { | |
return this.edges.length; | |
}; | |
Graph.Edge = function (tail, head) { | |
this.tail = tail; | |
this.head = head; | |
tail.edges.push(this); | |
head.edges.push(this); | |
}; | |
Graph.prototype.addVertex = function (name, value) { | |
if (!this.vertices[name]) { | |
this.vertices[name] = new Graph.Vertex(name, value); | |
this.length++; | |
} | |
else if (value) { | |
this.vertices[name].value = value; | |
} | |
return this.vertices[name]; | |
}; | |
Graph.prototype.addEdge = function (tail, head) { | |
return new Graph.Edge(this.addVertex(tail), this.addVertex(head)); | |
}; | |
module && module.exports = Graph; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment