Skip to content

Instantly share code, notes, and snippets.

@peter
Created May 11, 2015 08:46
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save peter/75aa6cf67f370b5bae4e to your computer and use it in GitHub Desktop.
JavaScript ramda example - imperative to functional refactoring
// 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));
@buzzdecafe
Copy link

I think can flatten(map) here be replaced with chain? 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

@peter
Copy link
Author

peter commented May 27, 2015

@buzzdecafe ah, that's cool, I hadn't added chain (flatMap) to my toolbox yet. Very useful, thanks!

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