Conway's Game of Life in JavaScript sprawling iterative function
Functional Techniques

The post was tagged with functional-programming but the example doesn't appear to make use of many functional-programming approaches.

You could use functional approaches when iterating over the states, like using Array.forEach(), Array.filter(), but bear in mind that each iteration involves calling a function so it won't be as efficient as using the for loops - especially considering that there are 4900 states!

For example, the loop starting with:


for (let i=0; i&lt;s.length; i++) {
    //check adjacents to determine if death or birth
}



Could be rewritten as:

this.states.forEach(function(state, i) {
    //check adjacents to determine if death or birth
});


And this block:


for (let j=0; j&lt;adjacents.length; j++) {
    if (s[adjacents[j]] == "X") {
        neighborCount++;
    }
}



Could be re-written utilizing Array.filter():

const neighborCount = adjacents.filter(function(adjacentIndex) {
    return s[adjacentIndex] == 'X';
  }).length;


which can eliminate the lines for initial assignment (i.e. let neighborCount = 0;) and re-assignment (i.e. neighborCount = 0;) at the end of each iteration. Note that const is used there because the value is not re-assigned (within the context of the loop).

These functional JS exercises are really helpful for those who want to learn more about using functional programming in JavaScript.

Single assignment for adjacent squares

Correct me if this leads to a difference in functionality but the array adjacents could be set with the following line:

const adjacents = [i-1, i+1, i-n-1, i-n, i-n+1, i+n-1, i+n, i+n+1];


That way it doesn't need to be re-assigned (and cleared after evaluating the neighbors) in every iteration (and the initial line let adjacents = []; can be removed from the start of cycle()).