Last active
August 29, 2015 14:19
-
-
Save StephanHoyer/cd436f448879c28745bd to your computer and use it in GitHub Desktop.
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
const directions = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]; | |
function evolve(currentCells) { | |
const equalTo = (a) => (b) => a[0] === b[0] && a[1] === b[1]; | |
const isCurrentlyAlive = (cell) => currentCells.some(equalTo(cell)); | |
const add = (a) => (b) => [a[0] + b[0], a[1] + b[1]] | |
const neighboursOf = (cell) => directions.map(add(cell)); | |
const notIn = (list) => (item) => !list.some(equalTo(item)); | |
const countNeighbours = (cell) => neighboursOf(cell).filter(isCurrentlyAlive).length; | |
const evolves = (cell) => | |
countNeighbours(cell) === 3 || | |
isCurrentlyAlive(cell) && countNeighbours(cell) === 2; | |
return currentCells.reduce((evolvedCells, cell) => | |
evolvedCells.concat( | |
neighboursOf(cell) | |
.filter(evolves) | |
.filter(notIn(evolvedCells)) | |
), []); | |
} | |
describe ('gol', () => { | |
it('should kill lonely', () => assert.deepEqual(evolve([[0,0]]), [])); | |
it('should kill 2', () => assert.deepEqual(evolve([[0,0], [1,0]]), [])); | |
it('should retain with 2 neighbours', | |
() => assert.deepEqual(evolve([[-1,-1], [0,0], [1, 1]]), [[0, 0]])); | |
it('should retain with 3 neighbours', | |
() => assert.deepEqual(evolve([[-1,-1], [0,0], [1, 1], [1, -1]]), [[0,-1],[0, 0],[1,0]])); | |
it('should create 1 when 3 parents', | |
() => assert.deepEqual(evolve([[0,0], [1,0], [2, 1]]), [[1, 0], [1, 1]])); | |
it('should kill overcrowded', | |
() => assert.deepEqual(evolve([[-1,1], [1,1], [1, -1], [-1,-1], [0, 0]]), [[-1,0],[0,1],[1,0],[0,-1]])); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment