Skip to content

Instantly share code, notes, and snippets.

@IkarosKappler
Created May 31, 2017 22:38
Show Gist options
  • Save IkarosKappler/4fb00049ac1286e0c39118c48f63eb02 to your computer and use it in GitHub Desktop.
Save IkarosKappler/4fb00049ac1286e0c39118c48f63eb02 to your computer and use it in GitHub Desktop.
A very simple Javascript graph/relation class for storing connecting nodes data.
/**
* A simple graph class.
*
* @author Ikaros Kappler
* @date 2017-05-30
* @modified 2017-05-31 Fixed the 'undirected' param and the getConnected function.
* @version 1.0.1
**/
var Graph = (function() {
// The constructor.
//
// The first param is a list of points of which type whatever you want/need.
// The graph class will not modify this list ever.
//
// The second param contains the settings (such as undirected).
var constructor = function( pointList, options ) {
options = options || {};
// A two-dimensional object { a : { b : true|false, ... }, ... }
var relation = {};
var setConnected = function(a,b,connected) {
if( connected ) {
if( !(a in relation) )
relation[a] = {};
relation[a][b] = connected; // This also allows weighted graphs.
} else {
if( a in relation && b in relation[a] ) {
delete( relation[a][b] );
// Keep our relation object clean.
if( Object.keys(relation[a]).length == 0 )
delete( relation[a] );
}
}
};
var getConnected = function(a,b,undirected) {
if( !(a in relation) || !(b in relation[a]) || !relation[a][b] ) {
if( undirected )
return getConnected(b,a,false);
else
return false;
} else {
return relation[a][b];
}
};
var _export = this;
_export.points = function() { return pointList; };
_export.connect = function(a,b,weight) { setConnected(a,b,weight||true); };
_export.unconnect = function(a,b) { setConnected(a,b,false); };
_export.connected = function(a,b) { return getConnected(a,b,options.undirected); };
};
return constructor;
} )();
// Self test
if( true ) {
var graph = new Graph( [], { undirected : true } );
console.log( '1-2 is connected? ' + graph.connected(1,2) );
graph.connect(1,2,10);
console.log( '1-2 should be connected now: ' + graph.connected(1,2) );
console.log( '2-1 should be connected now, too (undirected): ' + graph.connected(2,1) );
graph.unconnect(1,2);
console.log( '1-2 should be unconnected again: ' + graph.connected(1,2) );
};
@IkarosKappler
Copy link
Author

Minified version (532 Bytes):

var Graph=(function(){var a=function(c,e){e=e||{};var f={};var g=function(i,h,j){if(j){if(!(i in f)){f[i]={}}f[i][h]=j}else{if(i in f&&h in f[i]){delete (f[i][h]);if(Object.keys(f[i]).length==0){delete (f[i])}}}};var d=function(i,h,j){if(!(i in f)||!(h in f[i])||!f[i][h]){if(j){return d(h,i,false)}else{return false}}else{return f[i][h]}};var b=this;b.points=function(){return c};b.connect=function(i,h,j){g(i,h,j||true)};b.unconnect=function(i,h){g(i,h,false)};b.connected=function(i,h){return d(i,h,e.undirected)}};return a})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment