Skip to content

Instantly share code, notes, and snippets.

@JakeCoxon
Last active August 29, 2015 14:05
Show Gist options
  • Save JakeCoxon/7b4128254e41551359b4 to your computer and use it in GitHub Desktop.
Save JakeCoxon/7b4128254e41551359b4 to your computer and use it in GitHub Desktop.
var graph = new ImmutableGraph();
var graph1 = graph.addVertex( 2 )
var graph2 = graph1.addVertex( 1 );
var graph3 = graph2.addEdge( "A", [ 1, 2 ] );
// Using Immutable.js - https://github.com/facebook/immutable-js
function ImmutableGraph( vertices, edges, vertexMap, edgeMap ) {
this.vertices = Immutable.Set.from( vertices );
this.edges = Immutable.Set.from( edges );
this.vertexMap = Immutable.Map.from( vertexMap );
this.edgeMap = Immutable.Map.from( edgeMap );
}
ImmutableGraph.prototype.addVertex = function( vertex ) {
return new ImmutableGraph(
this.vertices.add( vertex ),
this.edges,
this.vertexMap.set( vertex, Immutable.Vector() ),
this.edgeMap
);
};
ImmutableGraph.prototype.addEdge = function( edge, vertices ) {
return new ImmutableGraph(
this.vertices,
this.edges.add( edge ),
this.vertexMap.withMutations( function( map ) {
for ( var i = 0; i < vertices.length; i ++ ) {
map.set( vertices[ i ], map.get( vertices[ i ] ).push( edge ) );
}
} ),
this.edgeMap.set( edge, Immutable.Vector.from( vertices ) )
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment