Created
May 25, 2015 18:54
-
-
Save peter/496e99b118e7688e2cab to your computer and use it in GitHub Desktop.
Ramda mapObj example
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
'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 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.
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
One step further, if you like. Since all you're doing with that
attributes parameter
is immediately passing it through, and sincemapObj
is curried, you can make this function points-free, via:And, since that's short enough, if that's the only use of
normalizeValue
, you could also inline it: