Skip to content

Commit fadbd21

Browse files
committed
Add error handling for shortest path
1 parent 8900781 commit fadbd21

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,12 @@ module.exports = function Graph(serialized){
213213
nodes().forEach(function (node){
214214
d[node] = Infinity;
215215
});
216+
if (d[source] !== Infinity) {
217+
throw new Error("Source node is not in the graph");
218+
}
219+
if (d[destination] !== Infinity) {
220+
throw new Error("Destination node is not in the graph");
221+
}
216222
d[source] = 0;
217223
}
218224

@@ -238,6 +244,9 @@ module.exports = function Graph(serialized){
238244
minNode = node;
239245
}
240246
});
247+
if (minNode === undefined) {
248+
throw new Error("No path exists.");
249+
}
241250
delete q[minNode];
242251
return minNode;
243252
}

test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,22 @@ describe("Graph", function() {
362362
assert.deepEqual(graph.shortestPath("s", "x"), ["s", "y", "t", "x"]);
363363
});
364364

365+
it("Should throw error if source node not in graph.", function (){
366+
var graph = Graph().addEdge("b", "c");
367+
assert.throws(() => graph.shortestPath("a", "c"), /Source node/);
368+
});
369+
370+
it("Should throw error if dest node not in graph.", function (){
371+
var graph = Graph().addEdge("b", "c");
372+
assert.throws(() => graph.shortestPath("b", "g"), /Destination node/);
373+
});
374+
375+
it("Should throw error if no path exists.", function (){
376+
var graph = Graph()
377+
.addEdge("a", "b")
378+
.addEdge("d", "e");
379+
assert.throws(() => graph.shortestPath("a", "e"), /No path/);
380+
});
365381
});
366382
});
367383

0 commit comments

Comments
 (0)