Last active
August 29, 2015 13:57
-
-
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.
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
/** | |
* 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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.