'Given an nested Array of winning conditions which are indexes compare another fixed length array and return true if given symbol matches those index
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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luminight |
