Skip to content

Instantly share code, notes, and snippets.

@wulymammoth
Created August 11, 2014 22:27
Show Gist options
  • Save wulymammoth/699cd416e20b0e05a97d to your computer and use it in GitHub Desktop.
Save wulymammoth/699cd416e20b0e05a97d to your computer and use it in GitHub Desktop.
From Imperative to Functional JS
/**
* 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] );
}
@alexhawkins
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment