Skip to content

Commit d60eac8

Browse files
committed
Fix bad edge creation on shortestPaths function
1 parent 8b5bcad commit d60eac8

2 files changed

Lines changed: 14 additions & 13 deletions

File tree

src/index.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -397,9 +397,14 @@ export function Graph(serialized?: Serialized) {
397397
removedEdges = [],
398398
weight = path.weight;
399399
while (weight) {
400-
removeEdge(path[0], path[1]);
401-
removeEdge(path[1], path[0]);
402-
removedEdges.push([path[0], path[1]]);
400+
if (hasEdge(path[0], path[1])) {
401+
removeEdge(path[0], path[1]);
402+
removedEdges.push([path[0], path[1]]);
403+
}
404+
if (hasEdge(path[1], path[0])) {
405+
removeEdge(path[1], path[0]);
406+
removedEdges.push([path[1], path[0]]);
407+
}
403408
try {
404409
path = shortestPath(source, destination);
405410
if (!path.weight || weight < path.weight) break;
@@ -408,10 +413,7 @@ export function Graph(serialized?: Serialized) {
408413
break;
409414
}
410415
}
411-
for (const [u, v] of removedEdges) {
412-
addEdge(u, v);
413-
addEdge(v, u);
414-
}
416+
for (const [u, v] of removedEdges) addEdge(u, v);
415417
return paths;
416418
}
417419

test.js

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ describe("Graph", function () {
427427
);
428428
});
429429

430-
it("Should compute shortest paths on six edges.", function () {
430+
it("Should compute shortest paths.", function () {
431431
var graph = Graph()
432432
.addEdge("a", "b")
433433
.addEdge("b", "c")
@@ -444,6 +444,9 @@ describe("Graph", function () {
444444
const nodes = ["a", "b", "c", "d", "e", "f"];
445445
assert.equal(graph.nodes().length, nodes.length);
446446
nodes.forEach((node) => assert(contains(graph.nodes(), node)));
447+
// check edges are still there and no new have been added
448+
assert.deepEqual(graph.hasEdge("a", "b"), true);
449+
assert.deepEqual(graph.hasEdge("b", "a"), false);
447450
});
448451
});
449452

@@ -458,11 +461,7 @@ describe("Graph", function () {
458461
});
459462

460463
function contains(arr, item) {
461-
return (
462-
arr.filter(function (d) {
463-
return d === item;
464-
}).length > 0
465-
);
464+
return arr.includes(item);
466465
}
467466

468467
function comesBefore(arr, a, b) {

0 commit comments

Comments
 (0)