Graph

by wio_dude

JavaScript

function Graph() {
    this.vertices = [];
}
Graph.prototype.addVertex = function (obj) {
    var id = this.vertices.length;
    this.vertices.push(new Vertex(id, obj));
    return id;
};
Graph.prototype.addArrow = function (id1, id2) {
    this.vertices[id1].connect(id2);
};
Graph.prototype.addEdge = function (id1, id2) {
    this.vertices[id1].connect(id2);
    this.vertices[id2].connect(id1);
};
Graph.prototype.isConnected = function (id1, id2) {
    return this.vertices[id1].isConnected(id2);
};

function Vertex(id, obj) {
    this.id = id;
    this.obj = obj;
    this.adjacency = {};
}
Vertex.prototype.getObject = function () {
    return this.obj;
};
Vertex.prototype.connect = function (id) {
    this.adjacency[id] = true;
};
Vertex.prototype.isConnected = function (id) {
    if (typeof this.adjacency[id] !== "undefined") {
        return this.adjacency[id] === true;
    }
    return false;
};