-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.mjs
56 lines (47 loc) · 1.44 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
export class Grid {
constructor(grid) {
this.grid = grid
}
get() {
return this.grid.map(row => [...row])
}
getAliveNeighborsFor(x, y) {
const isAlive = cell => cell === true
return [
this.grid[x - 1]?.[y - 1],
this.grid[x - 1]?.[y],
this.grid[x - 1]?.[y + 1],
this.grid[x]?.[y - 1],
this.grid[x]?.[y + 1],
this.grid[x + 1]?.[y - 1],
this.grid[x + 1]?.[y],
this.grid[x + 1]?.[y + 1],
].filter(isAlive).length
}
evolve() {
let newGrid = this.get()
this.grid.forEach((row, rowIndex) => {
row.forEach((cell, columIndex) => {
if (this.#shouldDie(rowIndex, columIndex)) {
newGrid[rowIndex][columIndex] = false
}
if (this.getAliveNeighborsFor(rowIndex, columIndex) === 3) {
newGrid[rowIndex][columIndex] = true
}
})
})
this.grid = newGrid
}
#shouldDie(rowIndex, columIndex) {
return (
this.#underpopulationAt(rowIndex, columIndex) ||
this.#overpopulation(rowIndex, columIndex)
)
}
#overpopulation(x, y) {
return this.grid[(x, y)] && this.getAliveNeighborsFor(x, y) > 3
}
#underpopulationAt(x, y) {
return this.grid[(x, y)] && this.getAliveNeighborsFor(x, y) < 2
}
}