Home > Net >  Given an nested Array of winning conditions which are indexes compare another fixed length array and
Given an nested Array of winning conditions which are indexes compare another fixed length array and

Time:03-28

 let testArray = Array(9).fill("") 
 
  const winConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];

  let xValue = "X";
  let oValue = "O";

The testArray gets populated with "X" and "O" on button click one at a time. So the end result should be for eg. if "X" is there on testArray index 0, 1, 2 return true

CodePudding user response:

function checkWin(value, array) {
    return winConditions.some((cond) =>
        cond.every((index) => array[index] == value));
}

console.log(checkWin(xValue, testArray));
console.log(checkWin(oValue, testArray));

some returns true if any of the values is true, every returns true if all of the values is true.

Therefore we check on each conditions if the value matches the all of the array values, and return true if any of these conditions is met.

  • Related