I'm new to JS, React and functional programming and am trying to make the Game of Life in React. My cycle function looks like iterative sprawl but all my attempts to refactor have been equally bad. The full code is here.
Any recommendations to make the function more elegant or efficient or best practices tips?
cycle() {
//a large array representing the grid with "X" for alive and "O" for dead
let s = this.state.squares;
let adjacents = [];
let neighborCount = 0;
let n = Math.sqrt(this.size);
let births = [];
let deaths = [];
for (let i=0; i<s.length; i++) {
//finds the eight neighboring squares for each square
adjacents.push(i-1, i+1, i-n-1, i-n, i-n+1, i+n-1, i+n, i+n+1);
for (let j=0; j<adjacents.length; j++) {
if (s[adjacents[j]] == "X") {
neighborCount++;
}
}
//determines if the central square will be born or die in this round
if (s[i] == "O" && neighborCount == 3) {
births.push(i);
}
else if ((s[i] == "X" && neighborCount < 2)
|| (s[i] == "X" && neighborCount > 3))
{
deaths.push(i);
}
neighborCount = 0;
adjacents = [];
}
//the grid array updates after all births and deaths for the round have been computed
for (let k=0; k<births.length; k++) {
s[births[k]] = "X";
}
for (let k=0; k<deaths.length; k++) {
s[deaths[k]] = "O";
}
births = [];
deaths = [];
this.setState({
squares: s
})
}