Skip to content

Instantly share code, notes, and snippets.

@polgfred
Last active December 11, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polgfred/18cf1e9b847e058214ec00b9a48dbc50 to your computer and use it in GitHub Desktop.
Save polgfred/18cf1e9b847e058214ec00b9a48dbc50 to your computer and use it in GitHub Desktop.
Extremely fast Game of Life implementation in 30 lines of JavaScript
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