Skip to content

Instantly share code, notes, and snippets.

@peter
Created May 25, 2015 18:54
Show Gist options
  • 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);
};
@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