Skip to content

Instantly share code, notes, and snippets.

@ThomasBurleson
Last active August 29, 2015 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasBurleson/9356484 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/9356484 to your computer and use it in GitHub Desktop.
Demonstration of reducing a messy, verbose `for loop` using functional approach for terse, concise solution.
/**
* Traditional solution: For-loop usage
*/
function buildEpisodes(markers)
{
var result = [],i, newEpisode;
if (markers && markers.length > 0) {
for (i = 0; i < markers.length; i++) {
newEpisode = makeEpisode(markers[i]);
if (newEpisode) {
result.push(newEpisode);
}
}
}
return result;
};
/**
* Functional Solution: Same logic, but concise and terse !!
* NOTE: includes morphic wrapping of `markers`
*/
function buildEpisodes_v2( markers )
{
var isNotNull = function( it ){ return it != null; };
return [ ].concat( markers ).map( makeEpisodes ).filter( isNotNull );
}
@sesteva
Copy link

sesteva commented Mar 5, 2014

Excellent example!
I was wondering.. if markers was an array, then you would not need to concat anything.
You should be able to say ' return markers.map( makeEpisodes ).filter( isNotNull );
Just curious to know if Im missing something.
Thanks!

@ThomasBurleson
Copy link
Author

@sesteva,
You are correct that [under normal conditions] I do not need the [ ].concat().

Now consider what happens if ( markers == null ) or markers is not an instance of Array?
Using [ ].concat() insures that it will always be an Array instance before the .map() invocation.

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