Skip to content

Instantly share code, notes, and snippets.

@boenfu
Created June 24, 2021 06:50
Show Gist options
  • Save boenfu/25082e33d36de96e4538af1984516277 to your computer and use it in GitHub Desktop.
Save boenfu/25082e33d36de96e4538af1984516277 to your computer and use it in GitHub Desktop.
CamelToDash
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