Skip to content

Instantly share code, notes, and snippets.

@bellentuck
Forked from Cfeusier/undirected-graph.js
Created January 31, 2017 17:51
Show Gist options
  • Save bellentuck/1d2cc2d72ccc859193f05419b57ca54e to your computer and use it in GitHub Desktop.
Save bellentuck/1d2cc2d72ccc859193f05419b57ca54e to your computer and use it in GitHub Desktop.
Simple undirected graph implementation in JavaScript
var Graph = function() {
this.nodes = {};
this.edges = {};
};
Graph.prototype.addNode = function(node) {
this.nodes[node] = node;
};
Graph.prototype.contains = function(node) {
return this.nodes[node] ? true : false;
};
Graph.prototype.removeNode = function(node) {
if (this.contains(node)) {
delete this.nodes[node];
}
};
Graph.prototype.hasEdge = function(fromNode, toNode) {
for (var key in this.edges) {
var searchOne = this.edges[key][0] === fromNode && this.edges[key][1] === toNode;
var searchTwo = this.edges[key][1] === fromNode && this.edges[key][0] === toNode;
if (searchOne || searchTwo) return true;
}
return false;
};
Graph.prototype.addEdge = function(fromNode, toNode) {
this.edges[fromNode] = [fromNode, toNode];
};
Graph.prototype.removeEdge = function(fromNode, toNode) {
if (this.hasEdge(fromNode, toNode)) {
delete this.edges[fromNode];
}
};
Graph.prototype.forEachNode = function(callback) {
for (var node in this.nodes) {
callback(node);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment