Skip to content

Instantly share code, notes, and snippets.

@janaz
Last active Nov 16, 2018
Embed
What would you like to do?
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