Skip to content

Commit

Permalink
Add a path creation function
Browse files Browse the repository at this point in the history
  • Loading branch information
cpettitt committed Sep 24, 2014
1 parent 722e6dd commit 14c5bce
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,16 @@ Graph.prototype.allEdges = function() {
return _.keys(this._edges);
};

Graph.prototype.path = function() {
var self = this,
segments = new Array(arguments.length - 1);
_.reduce(arguments, function(v, w, i) {
segments[i - 1] = self.edge(v, w);
return w;
});
return segments;
};

Graph.prototype.edge = function(v, w, name) {
var e = arguments.length === 1 ? v : this.edgeKey(v, w, name),
edge;
Expand Down
4 changes: 4 additions & 0 deletions src/bench.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ NODE_SIZES.forEach(function(size) {
g.allEdges();
});

runBenchmark("path" + nameSuffix, function() {
g.path("a", "b", "c", "d", "e");
});

runBenchmark("edge" + nameSuffix, function() {
g.edge("from", "to");
});
Expand Down
16 changes: 15 additions & 1 deletion test/graph-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ describe("Graph", function() {
});
});


describe("successors", function() {
it("returns undefined for a node that is not in the graph", function() {
expect(g.successors("a")).to.be.undefined;
Expand Down Expand Up @@ -148,6 +147,21 @@ describe("Graph", function() {
});
});

describe("path", function() {
it("creates a path of mutiple edges", function() {
g.path("a", "b", "c");
expect(g.hasEdge("a", "b")).to.be.true;
expect(g.hasEdge("b", "c")).to.be.true;
});

it("returns the segments of the path", function() {
var segments = g.path("a", "b", "c");
expect(segments).to.have.length(2);
expect(segments[0]).to.equal(g.edge("a", "b"));
expect(segments[1]).to.equal(g.edge("b", "c"));
});
});

describe("edge", function() {
it("creates the edge if it isn't part of the graph", function() {
g.node("a");
Expand Down

0 comments on commit 14c5bce

Please sign in to comment.