Created
December 14, 2014 09:20
-
-
Save Cfeusier/9b1c0020621382cbdedb to your computer and use it in GitHub Desktop.
Simple undirected graph implementation in JavaScript
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.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