Last active
March 3, 2024 18:53
-
-
Save Chooks22/83fba3e4276d4392bf6ed1d66a218900 to your computer and use it in GitHub Desktop.
TypeScript Pascal Case to Screaming Snake Case
This file contains hidden or 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
type PascalToScreamingSnake<T extends string, TInit = true, TMulti = false> = T extends `${infer Head}${infer Rest}` | |
? `${ | |
TInit extends true | |
? Uppercase<Head> | |
: Head extends Uppercase<Head> | |
? TMulti extends false | |
? `_${Head}` | |
: Rest extends `${infer Next}${string}` | |
? Next extends Uppercase<Next> | |
? Head | |
: `_${Head}` | |
: Head | |
: Uppercase<Head> | |
}${PascalToScreamingSnake<Rest, false, Head extends Uppercase<Head> ? true : false>}` | |
: '' | |
// PascalToScreamingSnake<'thisISDifficult'> -> THIS_IS_DIFFICULT | |
// PascalToScreamingSnake<'thisISNT'> -> THIS_ISNT | |
// PascalToScreamingSnake<'somethingEasyLikeThis'> -> SOMETHING_EASY_LIKE_THIS |
This file contains hidden or 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
// equivalent js, ugly iife coz ts and ternaries are ugly too | |
/** @param {string} T */ | |
function PascalToCamelCase(T, TInit = true, TMulti = false) { | |
if (T !== '') { | |
const [Head, Rest = ''] = [T[0], T.slice(1)] | |
return `${(() => { | |
if (TInit === true) { | |
return Uppercase(Head) | |
} else { | |
if (Head === Uppercase(Head)) { | |
if (TMulti === false) { | |
return `_${Head}` | |
} else { | |
if (Rest !== '') { | |
const Next = Rest[0] | |
if (Next === Uppercase(Next)) { | |
return Head | |
} else { | |
return `_${Head}` | |
} | |
} else { | |
return Head | |
} | |
} | |
} else { | |
return Uppercase(Head) | |
} | |
} | |
})()}${PascalToCamelCase(Rest, false, Head === Uppercase(Head))}` | |
} else { | |
return '' | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment