Skip to content

Instantly share code, notes, and snippets.

@manavm1990
Last active October 20, 2022 21:51
Show Gist options
  • Save manavm1990/8f3486f72ce38675811bb9928b66c482 to your computer and use it in GitHub Desktop.
Save manavm1990/8f3486f72ce38675811bb9928b66c482 to your computer and use it in GitHub Desktop.
const WINNING_INDICES = [
[0, 1, 2],
[0, 3, 6],
[0, 4, 8],
[1, 4, 7],
[2, 5, 8],
[2, 4, 6],
[3, 4, 5],
[6, 7, 8],
];
/**
* Calculate if there is a winner in a Tic-Tac-Toe game.
* @param {string[]} board - Contains either "X", "O" or "" to represent 9 spots on the board
* @param {string} - Either "X" or "O".
* @returns {boolean} Whether the player is the winner.
*/
export default (board, letter) =>
WINNING_INDICES.some((winningIndices) =>
winningIndices.every((winningIndex) => board[winningIndex] === letter)
);
import service from "./service";
describe("game service", () => {
it("should correctly determine the winner", () => {
const board = ["X", "X", "X", "O", "X", "O", "O", "X", "O"];
expect(service(board, "O")).toBe(false);
expect(service(board, "X")).toBe(true);
});
it("should not report a winner if there is none", () => {
const board = ["X", "O", "", "", "", "", "O", "X", ""];
expect(service(board, "O")).toBe(false);
expect(service(board, "X")).toBe(false);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment