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
I think can
flatten(map)
here be replaced withchain
? e.g.R.chain(R.take(LIMIT_PER_DAY), R.values(R.groupBy(R.prop('group'), widget.links))
And then it's a one-liner 😄
see e.g. http://bit.ly/1IDkEOH