Skip to content

Instantly share code, notes, and snippets.

@PetrSnobelt
Created June 27, 2018 14:30
Show Gist options
  • Save PetrSnobelt/3e527ba2940e4bbfd3e09b366e052e84 to your computer and use it in GitHub Desktop.
Save PetrSnobelt/3e527ba2940e4bbfd3e09b366e052e84 to your computer and use it in GitHub Desktop.
Game Of life in ES6 v3
// Using ES6
const nearZero = [[-1,-1], [0,-1], [1,-1],
[-1, 0], [1, 0],
[-1, 1], [0, 1], [1, 1]]
const neighboursOf = p =>
nearZero.map(n => [p[0] + n[0], p[1] + n[1]])
// arr.includes can't be used because [0, 0] !== [0, 0]
const contain = arr => pos =>
arr.some(x => x[0] === pos[0] && x[1] === pos[1])
const rules = (no, isAlive) =>
no === 3 || (no === 2 && isAlive)
const expandTestingArea = gen =>
gen.reduce((p, c) =>
p.concat(neighboursOf(c).filter(x => !contain(p)(x)))
, [])
const liveNeighboursInPrevGen = gen => pos =>
neighboursOf(pos).filter(contain(gen)).length // filter use Currying
const gol = gen => {
const isInPrevGen = contain(gen)
const noOfLiveNeigh = liveNeighboursInPrevGen(gen)
const ruleForPosition = p =>
rules(noOfLiveNeigh(p), isInPrevGen(p))
return expandTestingArea(gen).filter(ruleForPosition)
}
const blinker = [[0,0], [0,1], [0,2]];
const pentomimo = [[-1, 0], [-1, 1], [0, -1], [0, 0], [1, 0]];
var state = pentomimo;
state = gol(state);
console.log(state)
console.log(gol(gol(blinker)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment