Last active
December 11, 2019 16:59
-
-
Save polgfred/18cf1e9b847e058214ec00b9a48dbc50 to your computer and use it in GitHub Desktop.
Extremely fast Game of Life implementation in 30 lines of JavaScript
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
function gameOfLife(pop) { | |
const newpop = {}; | |
for (const coord in pop) { | |
const parts = coord.split(','); | |
const x = Number(parts[0]); | |
const y = Number(parts[1]); | |
for (let dx = -1; dx <= 1; ++dx) { | |
for (let dy = -1; dy <= 1; ++dy) { | |
newpop[`${x+dx},${y+dy}`] = true; | |
} | |
} | |
} | |
for (const coord in newpop) { | |
const parts = coord.split(','); | |
const x = Number(parts[0]); | |
const y = Number(parts[1]); | |
let neighbors = 0; | |
for (let dx = -1; dx <= 1; ++dx) { | |
for (let dy = -1; dy <= 1; ++dy) { | |
if (!(dx === 0 && dy === 0) && pop[`${x+dx},${y+dy}`]) { | |
neighbors++; | |
} | |
} | |
} | |
if (!(neighbors === 3 || (pop[coord] && neighbors === 2))) { | |
delete newpop[coord]; | |
} | |
} | |
return newpop; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment