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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've collected my Ramda examples here