Created
May 11, 2015 08:46
-
-
Save peter/75aa6cf67f370b5bae4e to your computer and use it in GitHub Desktop.
JavaScript ramda example - imperative to functional refactoring
This file contains 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
// BEFORE REFACTORING (IMPERATIVE) | |
var filteredLinks = []; | |
var weekdayCounts = {}; | |
// Limit to 4 links per weekday. | |
// Loop through all links and keep track of | |
// how many are in each weekday. | |
widget.links.forEach(function(link) { | |
var weekday = link.group; | |
if (weekdayCounts[weekday] === undefined) { | |
weekdayCounts[weekday] = 0; | |
} | |
if (weekdayCounts[weekday] < LIMIT_PER_DAY) { | |
filteredLinks.push(link); | |
weekdayCounts[weekday]++; | |
} | |
}); | |
widget.links = filteredLinks; | |
// AFTER REFACTORING (FUNCTIONAL) | |
var byGroup = R.values(R.groupBy(R.prop('group'), widget.links)); | |
widget.links = R.flatten(R.map(R.take(LIMIT_PER_DAY), byGroup)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@buzzdecafe ah, that's cool, I hadn't added chain (flatMap) to my toolbox yet. Very useful, thanks!