Provides data structure for directed graphs
A Graph object with the basic properties
var Graph = function () {
Object for holding vertices of the Graph
this.vertices = {};
Array of edges of the Graph
this.edges = [];
Length of the Graph, initially set to 0
this.length = 0;
};
Option name | Type | Description |
---|---|---|
name | string | Name of the vertex |
value | number | Value of the vertex |
Constructor for a vertex of {@link Graph}
Graph.Vertex = function (name, value) {
Store the name argument as a property *
this.name = name;
Create an empty array for edges
this.edges = [];
Store the value argument as a property
this.value = value;
};
Prototype function which returns the number of edges of a {@link Graph.Vertex}
Graph.Vertex.prototype.degree = function () {
return this.edges.length;
};
Option name | Type | Description |
---|---|---|
tail | Graph.Vertex | The tail vertex |
head | Graph.Vertex | The head vertex |
Constructor for edge of a {@link Graph}
Graph.Edge = function (tail, head) {
this.tail = tail;
this.head = head;
tail.edges.push(this);
head.edges.push(this);
};
Option name | Type | Description |
---|---|---|
name | string | Name of the new vertex |
value | number | Value of the new vertex |
Add a new {@link Graph.Vertex} or updates the value of an existing one
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];
};
Method for adding new {@link Graph.Edge}
Graph.prototype.addEdge = function (tail, head) {
return new Graph.Edge(this.addVertex(tail), this.addVertex(head));
};
Exports the {@link Graph}
module.exports = Graph;