Last active
June 25, 2022 10:47
-
-
Save fronterior/aed994babb17679fe3b8167c5dd195bb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const camelToSnake1 = (str) => str.replace(/[\w]([A-Z])/g, m => m[0] + '_' + m[1]).toLowerCase(); | |
const CAMEL_REGEX = /[\w]([A-Z])/g; | |
const cb = m => m[0] + '_' + m[1]; | |
const camelToSnake2 = (str) => str.replace(CAMEL_REGEX, cb).toLowerCase(); | |
const camelToSnake3 = (() => { | |
const CAMEL_REGEX = /[\w]([A-Z])/g; | |
const cb = m => m[0] + '_' + m[1]; | |
return (str) => str.replace(CAMEL_REGEX, cb).toLowerCase(); | |
})(); | |
const camelToSnake4 = (function (str) { return str.replace(this.CamelRegex, this.cb).toLowerCase(); }).bind({ | |
CamelRegex: /[\w]([A-Z])/g, | |
cb: ([a, b]) => a + '_' + b, | |
}); | |
const camelToSnake5 = Object.assign((str) => { return str.replace(camelToSnake5.CamelRegex, camelToSnake5.cb).toLowerCase(); }, { | |
CamelRegex: /[\w]([A-Z])/g, | |
cb: ([a, b]) => a + '_' + b, | |
}); | |
const camelToSnake6 = (str) => { | |
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 camelToSnake7 = (str) => ((c => 65 <= c && c <= 90 ? '' : '_')(str[0].charCodeAt(0)) + [...str].reduce((acc, char) => { | |
const code = char.charCodeAt(0); | |
return acc + (65 <= code && code <= 90 ? '_' + String.fromCharCode(code + 32) : char); | |
}, '')).slice(1); | |
const value = 'AbcdeAbcdeAbcdeAbcdeAbcdeAbcdeAbcdeAbcdeAbcdeAbcdeAbcdeAbcde'; | |
console.time('t1'); | |
camelToSnake1(value); | |
console.timeEnd('t1'); | |
console.time('t2'); | |
camelToSnake2(value); // fastest | |
console.timeEnd('t2'); | |
console.time('t3'); | |
camelToSnake3(value); // fastest | |
console.timeEnd('t3'); | |
console.time('t4'); | |
camelToSnake4(value); | |
console.timeEnd('t4'); | |
console.time('t5'); | |
camelToSnake5(value); | |
console.timeEnd('t5'); | |
console.time('t6'); | |
camelToSnake6(value); | |
console.timeEnd('t6'); | |
console.time('t7'); | |
camelToSnake7(value); | |
console.timeEnd('t7'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In Chrome, scope access is faster than field access