Skip to content

Commit d5d7d8c

Browse files
simonratnerzenkyomu
authored andcommitted
Fix findCycles to return single-node cycles
Match behaviour to that of isAcyclic.
1 parent 16f1055 commit d5d7d8c

3 files changed

Lines changed: 19 additions & 4 deletions

File tree

lib/alg/find-cycles.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,7 @@ var _ = require("../lodash"),
44
module.exports = findCycles;
55

66
function findCycles(g) {
7-
return _.filter(tarjan(g), function(cmpt) { return cmpt.length > 1; });
7+
return _.filter(tarjan(g), function(cmpt) {
8+
return cmpt.length > 1 || (cmpt.length === 1 && g.hasEdge(cmpt[0], cmpt[0]));
9+
});
810
}

test/alg/find-cycles-test.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,13 @@ describe("alg.findCycles", function() {
1414
expect(findCycles(g)).to.eql([]);
1515
});
1616

17-
it("returns a single entry for a cycle of 1 edge", function() {
17+
it("returns a single entry for a cycle of 1 node", function() {
18+
var g = new Graph();
19+
g.setPath(["a", "a"]);
20+
expect(sort(findCycles(g))).to.eql([["a"]]);
21+
});
22+
23+
it("returns a single entry for a cycle of 2 nodes", function() {
1824
var g = new Graph();
1925
g.setPath(["a", "b", "a"]);
2026
expect(sort(findCycles(g))).to.eql([["a", "b"]]);
@@ -30,8 +36,9 @@ describe("alg.findCycles", function() {
3036
var g = new Graph();
3137
g.setPath(["a", "b", "a"]);
3238
g.setPath(["c", "d", "e", "c"]);
33-
g.setNode("f");
34-
expect(sort(findCycles(g))).to.eql([["a", "b"], ["c", "d", "e"]]);
39+
g.setPath(["f", "g", "g"]);
40+
g.setNode("h");
41+
expect(sort(findCycles(g))).to.eql([["a", "b"], ["c", "d", "e"], ["g"]]);
3542
});
3643
});
3744

test/alg/is-acylic-test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ describe("alg.isAcylic", function() {
1515
expect(isAcyclic(g)).to.be.false;
1616
});
1717

18+
it("returns false if the graph has a cycle of 1 node", function() {
19+
var g = new Graph();
20+
g.setPath(["a", "a"]);
21+
expect(isAcyclic(g)).to.be.false;
22+
});
23+
1824
it("rethrows non-CycleException errors", function() {
1925
expect(function() { isAcyclic(undefined); }).to.throw();
2026
});

0 commit comments

Comments
 (0)