Last active
August 1, 2022 16:49
-
-
Save wffranco/2fecc900def050bbdd7591a1d98f8e52 to your computer and use it in GitHub Desktop.
Case Replacement
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
/** dash between num-letter */ const dbnl = [/(\d)([a-zA-Z])|([a-zA-Z])(\d)/g, '$1$3-$2$4']; | |
/** special characters to dash */ const sc2d = [/[^a-zA-Z0-9]+/g, '-']; | |
/** uppercase to dash */ const u2d = [/([A-Z])/g, '-$1']; | |
/** Common preconversion */ | |
const commonPre = fn => cacheStringFunction(str => fn(str.replace(...u2d).replace(...dbnl).replace(...sc2d))); | |
/** dash before a letter */ const dbl = /-([a-zA-Z])/g; | |
export const capitalizeWords = cacheStringFunction(str => str.toLowerCase().replace(/\b(\w)/g, (_, c) => (c ? c.toUpperCase() : ''))); | |
export const toCamelCase = commonPre(str => str.replace(dbl, (_, c) => (c ? c.toUpperCase() : ''))); | |
export const toKebabCase = commonPre(str => str.toLowerCase()); | |
export const toSnakeCase = commonPre(str => str.replace(dbl, (_, c) => (c ? `_${c}` : '')).toLowerCase()); | |
export const cacheStringFunction = fn => { | |
const cache = {}; | |
return str => cache[str] || (cache[str] = fn(str)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment