]> git.sesse.net Git - remoteglot/blobdiff - www/js/chessboard-0.3.0.js
Much faster findClosestPiece() (also generates much less garbage).
[remoteglot] / www / js / chessboard-0.3.0.js
index cbd46f4f4f064f0ac67620b7bdd93c4842635af7..ff2bf0384d686c2a6a2f83a9aa950e59dfbcacbe 100644 (file)
@@ -883,55 +883,26 @@ function squareDistance(s1, s2) {
   return yDelta;
 }
 
-// returns an array of closest squares from square
-function createRadius(square) {
-  var squares = [];
-
-  // calculate distance of all squares
-  for (var i = 0; i < 8; i++) {
-    for (var j = 0; j < 8; j++) {
-      var s = COLUMNS[i] + (j + 1);
-
-      // skip the square we're starting from
-      if (square === s) continue;
-
-      squares.push({
-        square: s,
-        distance: squareDistance(square, s)
-      });
-    }
-  }
-
-  // sort by distance
-  squares.sort(function(a, b) {
-    return a.distance - b.distance;
-  });
-
-  // just return the square code
-  var squares2 = [];
-  for (var i = 0; i < squares.length; i++) {
-    squares2.push(squares[i].square);
-  }
-
-  return squares2;
-}
-
 // returns the square of the closest instance of piece
 // returns false if no instance of piece is found in position
 function findClosestPiece(position, piece, square) {
-  // create array of closest squares from square
-  var closestSquares = createRadius(square);
-
-  // search through the position in order of distance for the piece
-  for (var i = 0; i < closestSquares.length; i++) {
-    var s = closestSquares[i];
+  let best_square = false;
+  let best_dist = 1e9;
+  for (var i = 0; i < COLUMNS.length; i++) {
+    for (var j = 1; j <= 8; j++) {
+      let other_square = COLUMNS[i] + j;
 
-    if (position.hasOwnProperty(s) === true && position[s] === piece) {
-      return s;
+      if (position[other_square] === piece && square != other_square) {
+        let dist = squareDistance(square, other_square);
+        if (dist < best_dist) {
+          best_square = other_square;
+          best_dist = dist;
+        }
+      }
     }
   }
 
-  return false;
+  return best_square;
 }
 
 // calculate an array of animations that need to happen in order to get