I am currently making a game that illustrates John Conways 'Game of Life' I've been learning about closures and the modular patterns and am trying to implement more of what I'm learning in Javascript. You can check out my repo here if your interested. All of these methods are inside a 'Game' object. I have it working, but am trying to limit variables and make it as functional as possible (passing the grid array between functions). I would like some advice on wether I should be keeping higher scope variable immutable or wether it doesnt matter.
Which solution is better practise, in terms of structure?
// initial grid
// will be bigger than this but is 3x3 for this question.
let grid = [
[1,0,0],
[0,1,0],
[0,0,1]
]
Solution 1: My initial way of solving:
function nextGrid(){
grid = applyRules(grid)
renderGrid(grid)
}
function applyRules(grid){
// makes changes
}
function renderGrid(grid){
// makes changes
}
// call nextGrid() to generate subsequent new grids.
Solution 2: Having looked into closures more, is this better?
function nextGrid() {
let prevGrid = grid;
return function(){
prevGrid = applyRules(prevGrid)
renderGrid(prevGrid)
}
}
function applyRules(prevGrid){
// makes changes
}
function renderGrid(grid){
// makes changes
}
const next = nextGrid();
// call next() to generate subsequent new grids.