Last active
March 22, 2019 21:03
-
-
Save ktilcu/1fae171dae31c2fa4709b1372d07838b to your computer and use it in GitHub Desktop.
connect-four.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const board = [ | |
[t,f,t,f], | |
[f,f,f,f], | |
[f,f,f,f], | |
[f,t,f,f], | |
] | |
/* | |
0 1 2 3 4 5 6 7 8 | |
0 O O O O O O O O B B = Winning col | |
1 X O O O A O O O B | |
2 O X O O O A O O B | |
3 O O X O O O A O B | |
4 O O O X O O O A O X and A = Winning DownRight Diagonals | |
5 O O O O O O O O A | |
6 O O O O O O O E O | |
7 O Y Y Y Y O E O O Y = Winning row | |
8 O O O O O E O O O | |
9 O O O O E O O O O E = Winning DownLeft Diagonal | |
*/ | |
const determineDiagonal = (width, height, x, y) => | |
const aggregateBoard = board => { | |
const width = board[0].length; | |
const height = board.length; | |
return Object.values(board | |
.reduce((acc, row, rowIndex) => | |
row.reduce((acc2, slot, columnIndex) => { | |
const columnName = `column${columnIndex}`; | |
const rowName = `row${rowIndex}`; | |
const drDiagonalName = `drDiag${determineDiagonal(...)}`; | |
const dlDiagonalName = `dlDiag${...}`; | |
if (!acc2[columnName] || Array.isArray(acc2[columnName])) acc2[columnName] = []; | |
// Same for rowName... | |
acc2[columnName].push(slot) | |
// same for others | |
return acc2; | |
}, acc) | |
,{})); // [ [true, false, true, false] ] | |
const isWinner = result /*[ttttf]*/ => result.reduce((cont, slot) => { | |
if (cont.length >= 4) return cont; | |
if (slot === false) return []; | |
cont.push(slot); | |
return cont; | |
}, []).length >= 4; | |
const omg = aggregateBoard(board).some(isWinner); | |
/* | |
// You can use Mocha to execute tests in the following way: | |
const mocha = require('./useMocha'); // This import sets up mocha, don't remove it. | |
const assert = require("assert"); | |
const sinon = require("sinon"); | |
const expect = require("expect"); | |
function foo(a, b) { | |
return a + b; | |
} | |
describe("Component", function() { | |
it("should add a + b", function() { | |
assert(foo(2, 2) === 4, "2+2 is not equal to 4"); | |
}); | |
}); | |
mocha.run(); // This call runs the tests. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment