Skip to content

Instantly share code, notes, and snippets.

@tmarshall
Created November 6, 2018 01:06
Show Gist options
  • Select an option

  • Save tmarshall/12c16053c72d49190efccf425bbca3b6 to your computer and use it in GitHub Desktop.

Select an option

Save tmarshall/12c16053c72d49190efccf425bbca3b6 to your computer and use it in GitHub Desktop.
Forces an object of possible snake case names to camel case (because why not)
const upperLettersMatch = /[A-Z]+/g
function camelToSnakeCase(str) {
return str
.replace(upperLettersMatch, (match, indx, baseString) => {
const replacement = match.length === 1 ? match :
match.length + indx === baseString.length ? match :
match.substr(0, match.length - 1) + '_' + match.substr(-1)
return (
(indx === 0 ? '' : '_') +
replacement
)
})
.toLowerCase()
}
const underscoreMatch = /_+([a-z])/g
function snakeToCamelCase(str) {
// expecting lower_snake_cased names
return str.replace(underscoreMatch, match => {
return match[1].toUpperCase()
})
}
function forceCamelCase(input) {
const output = {}
for (const key in input) {
const newKey = snakeToCamelCase(key)
output[newKey] = input[key]
if (key !== newKey) {
Object.defineProperty(output, key, {
get: function() {
return output[newKey]
},
set: function(val) {
output[newKey] = val
},
enumerable: false,
configurable: false
})
}
}
return output
}
/*
const x = { some_key: 12 }
const y = forceCamelCase(x)
y.someKey // 12
y.some_key // 12
Object.keys(y) // [ 'someKey' ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment