Game of Live in functional programming style.

by Daniel Suess

JavaScript

/**
 * WORK IN PROGRESS
 * Game of Live in functional programming style.
 *
 *
 *  1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
 *  2. Any live cell with more than three live neighbours dies, as if by overcrowding.
 *  3. Any live cell with two or three live neighbours lives on to the next generation.
 *  4. Any dead cell with exactly three live neighbours becomes a live cell.
 *
 *  Inspired from http://codingdojo.org/cgi-bin/index.pl?KataGameOfLife
 */

var ALIVE = "x",
    DEAD = ".";

function gameOfLive( worldAsList, handleLivingRulesFn, totalNumberOfRuns ) {

    // entry point
    handleRun( convertStringListTo2DArray( worldAsList ) );

    //---------
    // nested functions
    //---------

    function handleRun( worldArray, numberOfRunsDone ) {
        if ( !numberOfRunsDone ) {
            console.log( "Starting with:" );
            printArray( worldArray );
            numberOfRunsDone = 0;
        }

        worldArray.map( function ( rowValue, rowIndex ) {
            rowValue.map( function ( columnValue, columnIndex ) {
                //console.log( "[" + rowIndex + "," + columnIndex + "] = " + numberOfNeighbors + " status: " + columnValue + " --> " + handleLivingResult );
                // live update the world
                worldArray[ rowIndex ][ columnIndex ] = handleLivingRulesFn( columnValue, countNeighbors( worldArray, rowIndex, columnIndex ) );
            } )
        } );

        // increase runs
        numberOfRunsDone++;

        console.log( "Run " + numberOfRunsDone );
        printArray( worldArray );

        if ( numberOfRunsDone != totalNumberOfRuns ) {
            // recursive call
            handleRun( worldArray, numberOfRunsDone );
        }
    }

    function countNeighbors( worldArray, posX, posY ) {
        var counter = 0; // is counter variable in functional programming ok?

        // using 'undefined' evaluates to false for 'index out of bounds' handling
        //...