I'm creating a Tic Tac Toe solver algorithm. The idea is to iterate through each row, column and both diagonals and put them into a map in JavaScript. With that map I can run other logic to check for a winner and where that winner's position is.
I'm not building an actual TTT game nor am I writing any AI for now. My question is if there's a better way of achieving the same results without having to use two for loops to get the columns and second diagonals.
let board = [
['x','o','x'],
['o','o','o'],
['o','o','x']
];
const mapper = board => {
let map = {},
d1 = [],
d2 = [];
for (let i = 0; i < board.length; i++) {
let tmp = [];
// get all rows
map[`ROW${i}`] = board[i];
// get second diagonals
d2.push(board[i][board.length-1-i]);
for (let j = 0; j < board.length; j++) {
// get all columns
tmp.push(board[j][i]);
// get first diagonals
if (i === j) {
d1.push(board[i][j])
}
}
map[`COL${i}`] = tmp;
}
map[`DIA1`] = d1;
map[`DIA2`] = d2;
return map;
}
const checkForWinner = board => {
return mapper(board);
}
checkForWinner(board);