Created
June 24, 2021 06:50
-
-
Save boenfu/25082e33d36de96e4538af1984516277 to your computer and use it in GitHub Desktop.
CamelToDash
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
export type CamelToDash< | |
S extends string, | |
H = true | |
> = S extends `${infer S1}${infer S2}` | |
? S1 extends Uppercase<S1> | |
? H extends true | |
? `${Lowercase<S1>}${CamelToDash<S2, false>}` | |
: `-${Lowercase<S1>}${CamelToDash<S2, false>}` | |
: `${S1}${CamelToDash<S2, false>}` | |
: S; | |
export function camelToDash<T extends string>(str: T): CamelToDash<T> { | |
return Array.from(str) | |
.map((str, index) => { | |
let code = str.charCodeAt(0); | |
// 'A' 'Z' | |
if (code >= 65 || code <= 90) { | |
return index ? `-${str.toLowerCase()}` : str.toLowerCase(); | |
} | |
return str; | |
}) | |
.join('') as CamelToDash<T>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment