Skip to content

Instantly share code, notes, and snippets.

@peter
Created May 25, 2015 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter/496e99b118e7688e2cab to your computer and use it in GitHub Desktop.
Save peter/496e99b118e7688e2cab to your computer and use it in GitHub Desktop.
Ramda mapObj example
'use strict';
var R = require('ramda');
var blank = function(value) {
return value == null || (typeof value === 'string' && value.trim().length === 0);
};
var present = function(value) {
return !blank(value);
}
var nullify = function(value) {
return blank(value) ? null : value;
};
var trim = function(value) {
return value && value.trim();
};
/////////////////////////////////
// IMPERATIVE
/////////////////////////////////
var normalizeAttributes = function(attributes) {
Object.keys(attributes).forEach(function(key) {
var value = attributes[key];
if (present(value)) {
attributes[key] = trim(value);
} else {
attributes[key] = null;
}
});
return attributes;
};
/////////////////////////////////
// FUNCTIONAL
/////////////////////////////////
var normalizeValue = R.compose(trim, nullify);
var normalizeAttributes = function(attributes) {
return R.mapObj(normalizeValue, attributes);
};
@CrossEye
Copy link

One step further, if you like. Since all you're doing with that attributes parameter is immediately passing it through, and since mapObj is curried, you can make this function points-free, via:

var normalizeValue = R.compose(trim, nullify);
var normalizeAttributes = R.mapObj(normalizeValue);

And, since that's short enough, if that's the only use of normalizeValue, you could also inline it:

var normalizeAttributes = R.mapObj(R.compose(trim, nullify));

@peter
Copy link
Author

peter commented May 27, 2015

@CrossEye thanks for pointing out the points-free improvement (I guess I was using Venkats Office Space pattern of just taking one thing and passing it on). The oneliner option is nice too.

@peter
Copy link
Author

peter commented May 27, 2015

I've collected my Ramda examples here

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