refactorting
function nextGeneration(grid) { // pregenerated coords const neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]]; const neighboursCollector = (rowIndex, columnIndex) => ([x, y]) => grid[rowIndex + x][columnIndex + y]; const sum = (a, b) => a + b; return grid.map((row, rowIndex) => row.map((column, columnIndex) => { const isValid = rowIndex !== 0 && columnIndex !== 0 && rowIndex < grid.length - 1 && columnIndex < row.length - 1; if (!isValid) return 0; const currentCellValuesCollector = neighboursCollector(rowIndex, columnIndex); const neighboursCount = neighboursCords .map(currentCellValuesCollector) .reduce(sum); return +(neighboursCount === 3 || (column === 1 && neighboursCount === 2)); }) ); }
- function nextGeneration(grid) {
var neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]];return grid.map((r, ri) =>r.map((c, ci) => {if (ri !== 0 && ci !== 0 && ri < grid.length - 1 && ci < r.length - 1) {let neighboursCount = neighboursCords.reduce((s, v) => s += grid[ri + v[0]][ci + v[1]], 0);return 0 + (neighboursCount === 3 || (c === 1 && neighboursCount === 2));}return 0;}));- // pregenerated coords
- const neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]];
- const neighboursCollector = (rowIndex, columnIndex) => ([x, y]) => grid[rowIndex + x][columnIndex + y];
- const sum = (a, b) => a + b;
- return grid.map((row, rowIndex) =>
- row.map((column, columnIndex) => {
- const isValid = rowIndex !== 0 && columnIndex !== 0 &&
- rowIndex < grid.length - 1 && columnIndex < row.length - 1;
- if (!isValid) return 0;
- const currentCellValuesCollector = neighboursCollector(rowIndex, columnIndex);
- const neighboursCount = neighboursCords
- .map(currentCellValuesCollector)
- .reduce(sum);
- return +(neighboursCount === 3 || (column === 1 && neighboursCount === 2));
- })
- );
- }