Skip to content

Instantly share code, notes, and snippets.

@janaz
Last active November 16, 2018 14:37
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 janaz/d844537f1aab3d513944f053636a091d to your computer and use it in GitHub Desktop.
Save janaz/d844537f1aab3d513944f053636a091d to your computer and use it in GitHub Desktop.
no conditionals
const population = [ [], [], [], [], [], [] ];
population[3][4] = false;
//-------------------------------------------
const population = new Population();
const cell = new AliveCell();
const position = new Position(3, 4);
population.set(position, cell);
class Cell {}
class DeadCell extends Cell {}
class AliveCell extends Cell {}
Cell.DEAD = new DeadCell();
Cell.ALIVE = new AliveCell();
class Cell {
constructor(isAlive) {
this.isAlive = isAlive;
}
nextState(neighbours) {
if (this.isAlive && (neighbours === 2 || neighbours === 3)) {
return new Cell(true);
} else if (!this.isAlive && neighbours === 3) {
return new Cell(true);
} else {
return new Cell(false);
}
}
}
class AliveCell extends Cell {
nextState(neighbours) {
return [
Cell.DEAD, Cell.ALIVE, Cell.ALIVE,
Cell.DEAD, Cell.DEAD, Cell.DEAD,
Cell.DEAD, Cell.DEAD, Cell.DEAD
][neighbours - 1]
}
}
class DeadCell extends Cell {
nextState(neighbours) {
return [
Cell.DEAD, Cell.DEAD, Cell.ALIVE,
Cell.DEAD, Cell.DEAD, Cell.DEAD,
Cell.DEAD, Cell.DEAD, Cell.DEAD
][neighbours - 1]
}
}
const cell = population.cellAt(3, 4);
const neighbours = population.neighbours(3, 4);
nextPopulation.put(3, 4, cell.nextState(neighbours));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment