Skip to content

Commit

Permalink
Refactor: extract a function to get a cell next generation
Browse files Browse the repository at this point in the history
  • Loading branch information
NicolasPoirier committed Jul 19, 2024
1 parent 972eb92 commit 70e22ae
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/gameOfLife.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,22 @@ function isGenerative(liveNeighboursCount: number): boolean {
return liveNeighboursCount === 3
}

function computeCellNextGeneration(grid: Grid, cellRow: number, cellCol: number): State {
const liveNeighboursCount = getLiveNeighboursCount(grid, cellRow, cellCol)

if (isDeadly(liveNeighboursCount)) {
return State.DEAD
} else if (grid[cellRow][cellCol] === State.ALIVE || isGenerative(liveNeighboursCount)) {
return State.ALIVE
} else {
return State.DEAD
}
}

export function computeNextGeneration(grid: Grid): Grid {
return grid
.map((row, rowIndex) =>
row.map((_, colIndex) => {
const liveNeighboursCount = getLiveNeighboursCount(grid, rowIndex, colIndex)

if (isDeadly(liveNeighboursCount)) {
return State.DEAD
} else if (grid[rowIndex][colIndex] === State.ALIVE || isGenerative(liveNeighboursCount)) {
return State.ALIVE
} else {
return State.DEAD
}
}))
row.map((_, colIndex) =>
computeCellNextGeneration(grid, rowIndex, colIndex)
))
}

0 comments on commit 70e22ae

Please sign in to comment.