Skip to content

Instantly share code, notes, and snippets.

@methodin
Created January 2, 2012 13:34
Show Gist options
  • Save methodin/1550699 to your computer and use it in GitHub Desktop.
Save methodin/1550699 to your computer and use it in GitHub Desktop.
Graph
var Graph = function() {
this.nodes = {};
this.edges = {};
this.addNode = function(id, data) {
this.nodes[id] = data;
};
this.getNode = function(id) {
return this.nodes[id] || null;
};
// tests whether there is an edge from node x to node y.
this.adjacent = function(x, y) {
return (this.edges[x] !== undefined && this.edges[x][y] !== undefined ) || null;
};
// lists all nodes y such that there is an edge from x to y
this.neighbors = function(x) {
var neighbors = [];
if(this.edges[x] !== undefined) {
for(var neighbor in this.edges[x]) neighbors.push(neighbor);
}
return neighbors;
};
// adds to G the edge from x to y, if it is not there
this.add = function(x, y) {
if(this.adjacent(x,y) == null) {
if(this.edges[x] === undefined) this.edges[x] = {};
this.edges[x][y] = 0;
return true;
}
return false;
};
// removes the edge from x to y, if it is there
this.remove = function(x, y) {
if(this.edges[x] !== undefined && this.edges[x][y] !== undefined) {
delete this.edges[x][y];
return true;
}
return false;
};
// returns the value associated with the node x
this.getValue = function(x) {
return this.nodes[x] !== undefined ? this.nodes[x] : null;
};
// sets the value associated with the node x to a
this.setValue = function(x, a) {
this.nodes[i] = data;
};
// returns the value associated to the edge (x,y)
this.getEdgeValue = function(x, y) {
return this.edges[x] !== undefined && this.edges[x][y] !== undefined ? this.edges[x][y] : null;
};
// sets the value associated to the edge (x,y) to v
this.setEdgeValue = function(x, y, v) {
if(this.edges[x] !== undefined && this.edges[x][y] !== undefined) {
this.edges[x][y] = v;
return true;
}
return false;
};
};
var graph = new Graph();
graph.addNode('test', {});
graph.addNode('test2', {});
graph.addNode('test3', {});
graph.add('test','test2');
graph.add('test2','test3');
graph.setEdgeValue('test','test2',15);
graph.setEdgeValue('test2','test3',5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment