Last active
May 30, 2016 13:40
-
-
Save PetrSnobelt/55b692b557ec63b3d101e666bc236613 to your computer and use it in GitHub Desktop.
Game of Life in pure ES6 in 30 loc
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 near = [[-1,-1], [0, -1], [1, -1], | |
[-1, 0], [1, 0], | |
[-1, 1], [0, 1], [1, 1]]; | |
const neighbours = ([x, y]) => | |
near.map(([nx,ny]) => [x + nx, y + ny]) | |
//maybe using Symbol can help | |
Array.prototype.hash = function() {return this.join(',')} | |
const expand = (gen) => { | |
//lookup in array is not needed | |
existing = gen.map(x => {return [x.hash(), {pos:x, isLive: true, count:0}]}); | |
return gen.reduce((prev, curr) => { | |
neighbours(curr).map(pos => { | |
const existing = prev.get(pos.hash()); | |
if (existing) | |
existing.count++; //mutation :-( | |
else | |
prev.set(pos.hash(), {pos: pos, count: 1}) | |
}) | |
return prev | |
}, new Map(existing)); | |
} | |
const rules = ({count, isLive}) => | |
(count === 3 || (isLive && count == 2)) | |
const gol = (gen) => | |
Array.from(expand(gen), x => x[1]) | |
.filter(rules) | |
.map(x => x.pos); | |
const blinker = [[0,0], [0,1], [0,2]]; | |
const pentomimo = [[-1, 0], [-1, 1], [0, -1], [0, 0], [1, 0]]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment