function GraphNode(val) {
this.val = val;
this.edges = {};
}
function Graph() {
this.vertices = {};
}
Graph.prototype.addVertex = function (val) {
if (!this.vertices[val]) {
this.vertices[val] = new GraphNode(val);
}
};
Graph.prototype.removeVertex = function (val) {
if (this.vertices[val]) {
delete this.vertices[val];
Object.keys(this.vertices).forEach(
function (key, index) {
if (this.vertices[key].edges[val]) {
delete this.vertices[key].edges[val];
}
}.bind(this),
);
}
};
Graph.prototype.getVertex = function (val) {
return this.vertices[val];
};
Graph.prototype.addEdge = function (start, end) {
if (this.vertices[start] && this.vertices[end]) {
if (this.vertices[start].edges[end]) {
this.vertices[start].edges[end].weight += 1;
} else {
this.vertices[start].edges[end] = { weight: 1 };
}
}
};
Graph.prototype.removeEdge = function (start, end) {
if (this.vertices[start] && this.vertices[end]) {
if (this.vertices[start].edges[end]) {
delete this.vertices[start].edges[end];
}
}
};
Graph.prototype.getEdge = function (start, end) {
return this.vertices[start].edges[end] || null;
};
Graph.prototype.neighbors = function (val) {
return this.vertices[val] ? this.vertices[val].edges : null;
};
const graph = new Graph();
graph.addVertex(5);
graph.addVertex(2);
graph.addVertex(6);
graph.addVertex(7);
graph.addEdge(2, 5);
graph.addEdge(6, 7);
graph.addEdge(7, 5);
console.log(graph.getEdge(2, 5));
console.log(graph.getEdge(6, 7));
graph.removeVertex(5);
console.log(graph.getEdge(2, 5));
console.log(graph.neighbors(6));
console.log(graph.neighbors(5));