Skip to content

Instantly share code, notes, and snippets.

@teyfix
Created July 2, 2023 14:52
Show Gist options
  • Save teyfix/97fec95a97bfe37d7d87a4381ff9872f to your computer and use it in GitHub Desktop.
Save teyfix/97fec95a97bfe37d7d87a4381ff9872f to your computer and use it in GitHub Desktop.
Check the winner of a Tic Tac Toe game
export class InvalidBoardError extends Error {}
export default function ticTacToeWinner<T extends number | string>(
board: T[][],
): T | "Tie" {
// Check if the board is a valid game board
for (let i = 0; i < board.length; i++) {
if (board.length !== board[i].length) {
throw new InvalidBoardError();
}
}
const edge = board.length;
// Check rows
parent: for (let i = 0; i < edge; i++) {
const char = board[i][0];
for (let j = 1; j < edge; j++) {
if (board[i][j] !== board[i][j - 1]) {
continue parent;
}
}
return char;
}
// Check columns
parent: for (let i = 1; i < edge; i++) {
const char = board[i][0];
for (let j = 0; j < edge; j++) {
if (board[i][j] !== board[i - 1][j]) {
continue parent;
}
}
return char;
}
// Check diagonals
for (let i = 0; i < 2; i++) {
for (let j = 1; j < edge; j++) {
const char = board[0][0];
if (board[j][j] !== board[j - 1][j - 1]) {
break;
}
if (j === edge - 1) {
return char;
}
}
// Reverse the board for checking other diagonal
board = board.map((item) => item.reverse());
}
return "Tie";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment