I am writing a function that takes a 2d array that represents a grid for a tic tac toe game. Initially it is [[0, 0, 0], [0, 0, 0], [0, 0, 0]] and there is player 1 which is represented as 1 and player 2 as -1.
The function to check the winner should return the winner if there is actually a winner.
My attempt is this:
const checkIfWin = (b) => {
if (b[0][0] == b[0][1] && b[0][1] == b[0][2]) return b[0][0]
if (b[1][0] == b[1][1] && b[1][2] == b[1][1]) return b[1][0]
if (b[2][0] == b[2][1] && b[2][1] == b[2][2]) return b[2][2]
if (b[0][0] == b[1][0] && b[1][0] == b[2][0]) return b[2][0]
if (b[0][1] == b[1][1] && b[1][1] == b[2][1]) return b[2][1]
if (b[0][2] == b[1][2] && b[1][2] == b[2][2]) return b[2][2]
if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) return b[2][2]
if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) return b[2][0]
}
checkIfWin([ [ 1, 0, 0 ], [ 0, 1, 0 ], [ -1, -1, 1 ] ]) // 1
It works but I don't think it is really elegant or clean and I wonder if there is a better way to check a winner and return the winner?