typedash
Version:
modern, type-safe collection of utility functions
1 lines • 1.4 kB
Source Map (JSON)
{"version":3,"sources":["../../src/functions/constantCase/constantCase.ts"],"names":[],"mappings":";AAYO,SAAS,aAA+B,QAA4B;AACzE,MAAI,CAAC,UAAU,KAAK,MAAM,GAAG;AAC3B,WAAO;AAAA,EACT;AAEA,SAAO,OACJ,QAAQ,mBAAmB,OAAO,EAClC,QAAQ,WAAW,GAAG,EACtB,YAAY;AACjB","sourcesContent":["/**\n * Changes the casing of a string to constant case.\n * @param string The input string to change the casing of.\n * @returns A new string with the casing changed to constant case.\n * @example\n * ```ts\n * constantCase('fooBar') // 'FOO_BAR'\n * constantCase('foo bar') // 'FOO_BAR'\n * constantCase('foo-bar') // 'FOO_BAR'\n * constantCase('fooBar42') // 'FOO_BAR42'\n * ```\n */\nexport function constantCase<S extends string>(string: S): ConstantCase<S> {\n if (!/[a-z]+/i.test(string)) {\n return '' as ConstantCase<S>;\n }\n\n return string\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s-]+/g, '_')\n .toUpperCase() as ConstantCase<S>;\n}\n\n/**\n * Changes the casing of a string to constant case.\n * @see {@link constantCase}.\n */\nexport type ConstantCase<S extends string> = Uppercase<\n S extends `${infer S1}${infer S2}`\n ? `${S1 extends '-'\n ? '_'\n : S1 extends ' '\n ? '_'\n : S1 extends '_'\n ? '_'\n : S1 extends Capitalize<S1>\n ? `_${Lowercase<S1>}`\n : S1}${ConstantCase<S2>}`\n : S\n>;\n"]}