Step 8

The implementation of checkRow, checkColumn, checkMajorDiagonal and checkMinorDiagonal are fairly similar. Can you refactor the code and extract a function that factors the common behavior?

Solution

It is possible to do this, in particular for checkRow, checkColumn, as follows:

  • Add the following function
    function checkCells(rowFirst, rowLast, colFirst, colLast) {
      for (let row = rowFirst; row < rowLast; row++) {
        for (let col = colFirst; col < colLast; col++) {
          let index = toLinearIndex(row, col);
          if (board[index] !== markers[player]) return false;
        }
      }
      return true;
    }
    ```
    
  • Update checkRow
    function checkRow(row) {
      return checkCells(row, row + 1, 0, numCols);
    }
    
  • Update checkCol
    function checkColumn(col) {
      return checkCells(0, numRows, col, col + 1);
    }
    

To use checkCells for checking major/minor diagonal, we need to employ a more complex (and convoluted) logic.

The changes already make for a less readable code and a more complex and convoluted checkCells will change this situation for the worse. My preference would be keeping the code as is (without using checkCells at all).