Skip to content

Commit 441711d

Browse files
authored
Merge pull request #63 from jiminys/master
added isLeaf(v) function to graph
2 parents 8c372ee + c3cedd4 commit 441711d

3 files changed

Lines changed: 42 additions & 0 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
/build
22
/node_modules
3+
/.vscode

lib/graph.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,16 @@ Graph.prototype.neighbors = function(v) {
270270
}
271271
};
272272

273+
Graph.prototype.isLeaf = function (v) {
274+
var neighbors;
275+
if (this.isDirected()) {
276+
neighbors = this.successors(v);
277+
} else {
278+
neighbors = this.neighbors(v);
279+
}
280+
return neighbors.length === 0;
281+
};
282+
273283
Graph.prototype.filterNodes = function(filter) {
274284
var copy = new this.constructor({
275285
directed: this._isDirected,

test/graph-test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,37 @@ describe("Graph", function() {
529529
});
530530
});
531531

532+
describe("isLeaf", function() {
533+
it("returns false for connected node in undirected graph", function() {
534+
g = new Graph({directed: false});
535+
g.setNode("a");
536+
g.setNode("b");
537+
g.setEdge("a", "b");
538+
expect(g.isLeaf("b")).to.be.false;
539+
});
540+
it("returns true for an unconnected node in undirected graph", function() {
541+
g = new Graph({directed: false});
542+
g.setNode("a");
543+
expect(g.isLeaf("a")).to.be.true;
544+
});
545+
it("returns true for unconnected node in directed graph", function() {
546+
g.setNode("a");
547+
expect(g.isLeaf("a")).to.be.true;
548+
});
549+
it("returns false for predecessor node in directed graph", function() {
550+
g.setNode("a");
551+
g.setNode("b");
552+
g.setEdge("a", "b");
553+
expect(g.isLeaf("a")).to.be.false;
554+
});
555+
it("returns true for successor node in directed graph", function() {
556+
g.setNode("a");
557+
g.setNode("b");
558+
g.setEdge("a", "b");
559+
expect(g.isLeaf("b")).to.be.true;
560+
});
561+
});
562+
532563
describe("edges", function() {
533564
it("is empty if there are no edges in the graph", function() {
534565
expect(g.edges()).to.eql([]);

0 commit comments

Comments
 (0)