Skip to content

Instantly share code, notes, and snippets.

@fronterior
Created June 25, 2022 10:03
Show Gist options
  • Save fronterior/ffe57746e83d0d01d4a7462a0a518b5a to your computer and use it in GitHub Desktop.
Save fronterior/ffe57746e83d0d01d4a7462a0a518b5a to your computer and use it in GitHub Desktop.
const CAMEL_REGEX = /[\w]([A-Z])/g;
const cb = m => m[0] + '_' + m[1];
const camelToSnake1 = (str: string) => str.replace(CAMEL_REGEX, cb).toLowerCase();
const camelToSnake2 = (str: string) => {
const { length } = str;
let result = '', code = 0, i = 0;
for (i = 0; i < length; i++) {
code = str[i].charCodeAt();
if (65 <= code && code <= 90) {
result += '_';
result += String.fromCharCode(code + 32);
} else {
result += str[i];
}
}
return result.slice(1);
};
const camelToSnake3 = (...str: string[]) => ((c => 65 <= c && c <= 90 ? '' : '_')(str[0].charCodeAt0()) + str.reduce((acc, char) => {
const code = char.charCodeAt(0);
return acc + (65 <= code && code <= 90 ? '_' + String.fromCharCode(code + 32) : char);
}, '')).slice(1)
// fastest
const camelToSnake4 = (function (str: string) { return str.replace(this.CAMEL_REGEX, this.cb).toLowerCase(); }).bind({
CamelRegex: /[\w]([A-Z])/g,
cb: ([a, b]) => a + '_' + b,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment