Created
August 11, 2014 22:27
-
-
Save wulymammoth/699cd416e20b0e05a97d to your computer and use it in GitHub Desktop.
From Imperative to Functional JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Write a simple join function in the various styles: | |
* 1. Imperative | |
* 2. Object-oriented | |
* 3. Functional language | |
*/ | |
// Imperative | |
function simpleJoin( stringArray ) { | |
var accumulator = ''; | |
for ( var i = 0, l = stringArray.length; i < l; i++ ) { | |
accumulator = accumulator + stringArray[i]; | |
} | |
return accumulator; | |
} | |
// Object-oriented | |
Array.prototype.simpleJoin = function() { | |
var accumulator = ''; | |
for ( var i = 0, l = this.length; i < l; i++ ) { | |
accumulator = accumulator + this[i]; | |
} | |
return accumulator; | |
}; | |
// Functional (imperative) | |
function simpleJoin( stringArray, i, accumulator ) { | |
if ( i === stringArray.length ) { | |
return accumulator; | |
} else { | |
return simpleJoin( stringArray, i+1, accumulator+stringArray[i] ); | |
} | |
} | |
// Pure Functional | |
function simpleJoin( stringArray, i, accumulator ) { | |
return ( i === stringArray.length ) ? accumulator : | |
simpleJoin( stringArray, i+1, accumulator + stringArray[i] ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice post David. I was practicing this exact exercise last night too after reading about it the Functional programming article you linked to. Definitely the Imperative and OO methods come the most naturally. What is the advantage of the Pure Functional in a situation like this?