Skip to content

Commit c3cedd4

Browse files
committed
implemented isLeaf
1 parent 0bc95eb commit c3cedd4

3 files changed

Lines changed: 26 additions & 15 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: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,21 @@ describe("Graph", function() {
514514
});
515515
});
516516

517+
describe("neighbors", function() {
518+
it("returns undefined for a node that is not in the graph", function() {
519+
expect(g.neighbors("a")).to.be.undefined;
520+
});
521+
522+
it("returns the neighbors of a node", function() {
523+
g.setEdge("a", "b");
524+
g.setEdge("b", "c");
525+
g.setEdge("a", "a");
526+
expect(_.sortBy(g.neighbors("a"))).to.eql(["a", "b"]);
527+
expect(_.sortBy(g.neighbors("b"))).to.eql(["a", "c"]);
528+
expect(_.sortBy(g.neighbors("c"))).to.eql(["b"]);
529+
});
530+
});
531+
517532
describe("isLeaf", function() {
518533
it("returns false for connected node in undirected graph", function() {
519534
g = new Graph({directed: false});
@@ -545,21 +560,6 @@ describe("Graph", function() {
545560
});
546561
});
547562

548-
describe("neighbors", function() {
549-
it("returns undefined for a node that is not in the graph", function() {
550-
expect(g.neighbors("a")).to.be.undefined;
551-
});
552-
553-
it("returns the neighbors of a node", function() {
554-
g.setEdge("a", "b");
555-
g.setEdge("b", "c");
556-
g.setEdge("a", "a");
557-
expect(_.sortBy(g.neighbors("a"))).to.eql(["a", "b"]);
558-
expect(_.sortBy(g.neighbors("b"))).to.eql(["a", "c"]);
559-
expect(_.sortBy(g.neighbors("c"))).to.eql(["b"]);
560-
});
561-
});
562-
563563
describe("edges", function() {
564564
it("is empty if there are no edges in the graph", function() {
565565
expect(g.edges()).to.eql([]);

0 commit comments

Comments
 (0)