How can I speed up my check detection in Javascript? I am trying to write a simple chess engine in Javascript. It performs very slowly but I have finally rooted down the problem to check detection. How might I speed up this check detection? If you have any questions or need any clarifications feel free to ask.

Check detection takes approximately 10-20 milliseconds.

Here is the code:

function availableInvalidSpots(board, player) {
    let validPositions = [];
    let playerPositions = getAllPieces(player, board);
    for (position = 0; position &lt; playerPositions.length; position++) {
        validPositions.push(getUncheckedMoves(playerPositions[position], board));
    }
    return validPositions;
}

function getPiecePosition(piece, board) {
    for (rowCount = 0; rowCount &lt; 8; rowCount++) {
        for (columnCount = 0; columnCount &lt; 8; columnCount++) {
            if (board[rowCount][columnCount].pieceName == piece) {
                return {
                    x: columnCount,
                    y: rowCount
                };
            }
        }
    }
}

function getPlayerInfo(pieceType) {
    return (pieceType == blackPieces ? {
        king: "blackKing",
        opponent: whitePieces
    } : {
        king: "whiteKing",
        opponent: blackPieces
    });
}

function setPlayerInfo(player, board) {
    let PLAYER = getPlayerInfo(player);
    let opponent = PLAYER.opponent;
    king = PLAYER.king;
    kingPosition = getPiecePosition(king, board);
    opponentMoves = availableInvalidSpots(board, opponent);
}

function isPlayerInCheck(player, board) {
    setPlayerInfo(player, board);

    for (opponentMove = 0; opponentMove &lt; opponentMoves.length; opponentMove++) {
        for (square = 0; square &lt; opponentMoves[opponentMove].move.length; square++) {
            if (opponentMoves[opponentMove].move[square].to.x == kingPosition.x &amp;&amp; opponentMoves[opponentMove].move[square].to.y == kingPosition.y) {
                return true;
            }
        }
    }
    return false;
}
It looks like your engine is using very simple for loop and arrays. Your code simply loop over again and again, possibly repeat each search iteration.

That’s obviously not good. Chess engine can’t run fast if it has to loop like that. If the position had no check surely all CPU time wasted?

My recommendation is change your data structure to a bitboard. Bitboard will allow you run check detection quickly, just do a AND the pieces your opponent can attack and your king position.