From c78568ee5d867b6f66bab0ef4b16f6e78a64abb1 Mon Sep 17 00:00:00 2001 From: "Steinar H. Gunderson" Date: Mon, 26 Dec 2022 00:10:37 +0100 Subject: [PATCH] Much faster findClosestPiece() (also generates much less garbage). --- www/js/chessboard-0.3.0.js | 55 +++++++++----------------------------- 1 file changed, 13 insertions(+), 42 deletions(-) diff --git a/www/js/chessboard-0.3.0.js b/www/js/chessboard-0.3.0.js index cbd46f4..ff2bf03 100644 --- a/www/js/chessboard-0.3.0.js +++ b/www/js/chessboard-0.3.0.js @@ -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 -- 2.39.2