Skip to content

Commit 8f9f800

Browse files
committed
Fixed missed use case of no path found
1 parent 83dc856 commit 8f9f800

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

astar.js

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,17 @@ var astar = {
4646
node.parent = null;
4747
}
4848
},
49-
49+
cleanNodes:function(hitNodes){
50+
for (var i = 0; i < hitNodes.length; i++) {
51+
var node = hitNodes[i];
52+
node.f = 0;
53+
node.g = 0;
54+
node.h = 0;
55+
node.visited = false;
56+
node.closed = false;
57+
node.parent = null;
58+
}
59+
},
5060
/**
5161
* Perform an A* Search on a graph given a start and end node.
5262
* @param {Graph} graph
@@ -71,7 +81,7 @@ var astar = {
7181

7282
openHeap.push(start);
7383

74-
var cleaner = [];
84+
var hitNodes = [];
7585
while(openHeap.size() > 0) {
7686

7787
// Grab the lowest f(x) to process next. Heap keeps this sorted for us.
@@ -80,15 +90,7 @@ var astar = {
8090
// End case -- result has been found, return the traced path.
8191
if(currentNode === end) {
8292
var path = pathTo(currentNode);
83-
for (var c = 0; c < cleaner.length; c++) {
84-
var node = cleaner[c];
85-
node.f = 0;
86-
node.g = 0;
87-
node.h = 0;
88-
node.visited = false;
89-
node.closed = false;
90-
node.parent = null;
91-
}
93+
astar.cleanNodes(hitNodes);
9294
return path;
9395
}
9496

@@ -119,7 +121,7 @@ var astar = {
119121
neighbor.h = neighbor.h || heuristic(neighbor, end);
120122
neighbor.g = gScore;
121123
neighbor.f = neighbor.g + neighbor.h;
122-
cleaner.push(neighbor);
124+
hitNodes.push(neighbor);
123125
if (closest) {
124126
// If the neighbour is closer than the current closestNode or if it's equally close but has
125127
// a cheaper path than the current closest node then it becomes the closest node
@@ -141,9 +143,12 @@ var astar = {
141143
}
142144

143145
if (closest) {
144-
return pathTo(closestNode);
146+
var closestPath = pathTo(closestNode);
147+
astar.cleanNodes(hitNodes);
148+
return closestPath;
145149
}
146150

151+
astar.cleanNodes(hitNodes);
147152
// No result was found - empty array signifies failure to find path.
148153
return [];
149154
},

0 commit comments

Comments
 (0)