Skip to content

Instantly share code, notes, and snippets.

@judsonbsilva
Last active October 6, 2016 01:51
Show Gist options
  • Save judsonbsilva/49f1aeccb8c42ded91bc79cfbbd8cffc to your computer and use it in GitHub Desktop.
Save judsonbsilva/49f1aeccb8c42ded91bc79cfbbd8cffc to your computer and use it in GitHub Desktop.
A Graph representation with JavaScript ES6
class Graph {
constructor(){
this.nodes = [];
this.edges = [];
}
addNode( node ){
if( !this.hasNode(node) )
this.nodes.push(node);
}
randomSeed( number ){
let i,j;
for(i = 1; i <= number; i++)
this.addNode(i);
for(i = 1; i <= number; i++)
for(j = 1; j <= number; j++)
if( i != j )
this.addEdge(i,j, Math.floor( Math.random() * 100 ));
}
hasNode( node ){
for(var i in this.nodes )
if( this.nodes[i] == node )
return true;
return false;
}
hasEdge( n1, n2 ){
const edges = this.edges;
for(var i in edges){
if(
( edges[i][0] == n1 && edges[i][1] == n2 ) ||
( edges[i][1] == n1 && edges[i][0] == n2 )
)
return true;
}
return false;
}
addEdge( n1, n2, size){
if(
this.hasNode(n1) &&
this.hasNode(n2) &&
!this.hasEdge(n1, n2) ){
this.edges.push([n1,n2, size || 0]);
}
}
}
var test = new Graph();
test.randomSeed(15);
console.log(test.edges.length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment