Lazy refactoring, reduced 8 if statements.
function nextGeneration(grid) { return grid.map((row, rowIndex) => { return row.map((cell, colIndex) => { if (rowIndex !== 0 && colIndex !== 0 && rowIndex < grid.length - 1 && colIndex < row.length - 1) { let neighboursCount = (grid[rowIndex][colIndex + 1] === 1) + (grid[rowIndex][colIndex - 1] === 1) + (grid[rowIndex + 1][colIndex] === 1) + (grid[rowIndex - 1][colIndex] === 1) + (grid[rowIndex + 1][colIndex + 1] === 1) + (grid[rowIndex + 1][colIndex - 1] === 1) + (grid[rowIndex - 1][colIndex + 1] === 1) + (grid[rowIndex - 1][colIndex - 1] === 1); if (cell === 1) { if (neighboursCount === 2 || neighboursCount === 3 ) { return 1; } } else { if (neighboursCount === 3 ) { return 1; } } return 0; } return 0; }); }); }
- function nextGeneration(grid) {
- return grid.map((row, rowIndex) => {
- return row.map((cell, colIndex) => {
- if (rowIndex !== 0 && colIndex !== 0 && rowIndex < grid.length - 1 && colIndex < row.length - 1) {
let neighboursCount = 0;if (grid[rowIndex][colIndex + 1] === 1) neighboursCount++;if (grid[rowIndex][colIndex - 1] === 1) neighboursCount++;if (grid[rowIndex + 1][colIndex] === 1) neighboursCount++;if (grid[rowIndex - 1][colIndex] === 1) neighboursCount++;if (grid[rowIndex + 1][colIndex + 1] === 1) neighboursCount++;if (grid[rowIndex + 1][colIndex - 1] === 1) neighboursCount++;if (grid[rowIndex - 1][colIndex + 1] === 1) neighboursCount++;if (grid[rowIndex - 1][colIndex - 1] === 1) neighboursCount++;- let neighboursCount = (grid[rowIndex][colIndex + 1] === 1) + (grid[rowIndex][colIndex - 1] === 1) + (grid[rowIndex + 1][colIndex] === 1) + (grid[rowIndex - 1][colIndex] === 1) + (grid[rowIndex + 1][colIndex + 1] === 1) + (grid[rowIndex + 1][colIndex - 1] === 1) + (grid[rowIndex - 1][colIndex + 1] === 1) + (grid[rowIndex - 1][colIndex - 1] === 1);
- if (cell === 1) {
- if (neighboursCount === 2 || neighboursCount === 3 ) {
- return 1;
- }
- } else {
- if (neighboursCount === 3 ) {
- return 1;
- }
- }
- return 0;
- }
- return 0;
- });
- });
- }