Skip to content

Instantly share code, notes, and snippets.

@andresilveirah
Created May 10, 2016 13:25
Show Gist options
  • Save andresilveirah/a6a4f4cede8f41cda6bfaaae5234edf2 to your computer and use it in GitHub Desktop.
Save andresilveirah/a6a4f4cede8f41cda6bfaaae5234edf2 to your computer and use it in GitHub Desktop.
A short helper to 'underscorify' strings and objects (taking nesting into account). It uses underscore (though vanilla js shouldn't be difficult) and ES6 syntax.
import _ from 'underscore';
// Convert fooBar to foo_bar
const underscoreCase = function(str) {
return str.replace(/([a-z])([A-Z]+)/g, function(terms) {
return terms[0] + '_' + terms[1].toLowerCase();
});
};
const underscorify = function(stringOrObject) {
if (_.isString(stringOrObject)) {
return underscoreCase(stringOrObject);
}
return Object.keys(object || {}).reduce(function(memo, key) {
const value = object[key];
const newValue = _.isObject(value) ? underscorifyObject(value) : value;
memo[underscoreCase(key)] = newValue;
return memo;
}, {});
};
export default underscorify;
// specs for it
describe('underscorify', function() {
it('should transform fooBar into foo_bar', function() {
expect(underscorify('fooBar')).toEqual('foo_bar');
});
it('should transform { fooBar: \'foo\' } into { foo_bar: \'foo\' }', function() {
expect(underscorify({ fooBar: 'bar' })).toEqual({ foo_bar: 'bar' });
});
it('should also transform nested objects', function() {
expect(underscorify({
fooBar: 'bar',
nestedAttr: {
fooBar: 'bar'
}
})).toEqual({
foo_bar: 'bar',
nested_attr: {
foo_bar: 'bar'
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment