Home > other >  More efficient JavaScript code for finding variables in nested arrays from another random array
More efficient JavaScript code for finding variables in nested arrays from another random array

Time:09-08

I am relatively new to JavaScript and I am writing some test code to check win lines in a TicTacToe (Noughts and Crosses) game.

After several iterations this is what I have come up with, but I still feel that it is unwieldy and relies too much on global variables.

Is there a better way to write this code?

const wins = [[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]];

const moves = [0,5,2,4,3]; // example list of moves

var winLine = [];
const won = [true, true, true];

wins.forEach(function (win) {
win.forEach((square) => winLine.push(moves.some((move) => square == move)));
if(JSON.stringify(winLine) == JSON.stringify(won)){
  logWin();
 } else {
  winLine =[];
 }
});

 function logWin() {
  console.log("win");
 }

CodePudding user response:

You could filter the winning positions and get an array of lines.

If this array is empty, no win.

This code utilizes some array methods:

const
    wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]],
    moves = [0, 5, 2, 4, 3],
    winLines = wins.filter(p => p.every(v => moves.includes(v)));

console.log(winLines);

CodePudding user response:

You could go for a completely different approach where you first apply the moves on a bit board (of 9 bits), and then verify via bit operations whether there is a win:

// Patterns of winning lines
const wins = [0x7, 0x38, 0x1C0, 0x49, 0x92, 0x124, 0x111, 0x54];

const moves = [0,5,2,4,3]; // example list of moves

// Convert moves to bit board
const pattern = moves.reduce((acc, i) => acc | (1 << i), 0);
// Overlay each winning line pattern to see if there is a match
const hasWon = wins.some(win => (win & pattern) === win);

console.log(hasWon);

  • Related