Skip to content

Commit

Permalink
Performance improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
cpettitt committed Sep 24, 2014
1 parent d7ce6aa commit 72c55e7
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions lib/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,16 @@ function Graph(opts) {
this._nodes = {};

// v -> edgeObj
this._in= {};
this._in = {};

// v -> edgeObj
this._out= {};
this._out = {};

// e -> edgeObj
this._edgeObjs = {};

// e -> attrs
this._edges = {};
this._edgeAttrs = {};
}

/* Number of nodes in the graph. Should only be changed by the implementation. */
Expand Down Expand Up @@ -131,7 +134,7 @@ Graph.prototype.edgeCount = function() {
};

Graph.prototype.allEdges = function() {
return _.map(_.keys(this._edges), edgeIdToObj);
return _.values(this._edgeObjs);
};

Graph.prototype.path = function() {
Expand All @@ -150,7 +153,7 @@ Graph.prototype.edge = function(v, w, name) {
var e = (arguments.length === 1
? edgeObjToId(this.isDirected, arguments[0])
: edgeArgsToId(this.isDirected, v, w, name));
var edge = this._edges[e];
var edge = this._edgeAttrs[e];
if (edge) {
return edge;
}
Expand All @@ -169,10 +172,13 @@ Graph.prototype.edge = function(v, w, name) {
this.node(v);
this.node(w);

edge = _.merge({}, this.edgeAttrDefs);
this._edges[e] = edge;
this._out[v][e] = true;
this._in[w][e] = true;
edge = this._edgeAttrs[e] = _.merge({}, this.edgeAttrDefs);

var edgeObj = edgeIdToObj(e);
Object.freeze(edgeObj);
this._edgeObjs[e] = edgeObj;
this._out[v][e] = edgeObj;
this._in[w][e] = edgeObj;
this._edgeCount++;
return edge;
}
Expand All @@ -182,37 +188,38 @@ Graph.prototype.hasEdge = function(v, w, name) {
var e = (arguments.length === 1
? edgeObjToId(this.isDirected, arguments[0])
: edgeArgsToId(this.isDirected, v, w, name));
return _.has(this._edges, e);
return _.has(this._edgeAttrs, e);
};

Graph.prototype.removeEdge = function(v, w, name) {
var e = (arguments.length === 1
? edgeObjToId(this.isDirected, arguments[0])
: edgeArgsToId(this.isDirected, v, w, name));
if (_.has(this._edges, e)) {
if (_.has(this._edgeAttrs, e)) {
if (arguments.length === 1) {
v = arguments[0].v;
w = arguments[0].w;
name = arguments[0].name;
}
delete this._out[v][e];
delete this._in[w][e];
delete this._edges[e];
delete this._edgeAttrs[e];
delete this._edgeObjs[e];
this._edgeCount--;
}
};

Graph.prototype.inEdges = function(v) {
var inV = this._in[v];
if (inV) {
return _.map(_.keys(inV), edgeIdToObj);
return _.values(inV);
}
};

Graph.prototype.outEdges = function(v) {
var outV = this._out[v];
if (outV) {
return _.map(_.keys(outV), edgeIdToObj);
return _.values(outV);
}
};

Expand Down

0 comments on commit 72c55e7

Please sign in to comment.