UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 1.43 kB
{"version":3,"file":"constantCase-BbzF3WeM.cjs","names":[],"sources":["../src/functions/constantCase/constantCase.ts"],"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"],"mappings":";;;;;;;;;;;;;;AAYA,SAAgB,aAA+B,QAA4B;AACzE,KAAI,CAAC,UAAU,KAAK,OAAO,CACzB,QAAO;AAGT,QAAO,OACJ,QAAQ,mBAAmB,QAAQ,CACnC,QAAQ,WAAW,IAAI,CACvB,aAAa"}