|
| 1 | +export default function useCamelize() { |
| 2 | + /** |
| 3 | + * Converts a dash-separated string to PascalCase |
| 4 | + * @param input - The dash-separated string to convert (e.g., "hello-world") |
| 5 | + * @returns The PascalCase string (e.g., "HelloWorld") |
| 6 | + * @example |
| 7 | + * toPascalCase("hello-world") // returns "HelloWorld" |
| 8 | + * toPascalCase("my-component-name") // returns "MyComponentName" |
| 9 | + */ |
| 10 | + function toPascalCase(input: string): string { |
| 11 | + // Handle edge cases |
| 12 | + if (!input || typeof input !== 'string') { |
| 13 | + return '' |
| 14 | + } |
| 15 | + |
| 16 | + // Split the string at dash characters and filter out empty parts |
| 17 | + const wordParts = input.split('-').filter(part => part.length > 0) |
| 18 | + |
| 19 | + // Convert each word: first character to uppercase, rest to lowercase |
| 20 | + const pascalCaseWords = wordParts.map(capitalizeFirstLetter) |
| 21 | + |
| 22 | + // Join all words together |
| 23 | + return pascalCaseWords.join('') |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Capitalizes the first letter of a word and keeps the rest as-is |
| 28 | + * @param word - The word to capitalize |
| 29 | + * @returns The word with first letter capitalized |
| 30 | + */ |
| 31 | + function capitalizeFirstLetter(word: string): string { |
| 32 | + if (word.length === 0) { |
| 33 | + return '' |
| 34 | + } |
| 35 | + |
| 36 | + const firstCharacter = word[0]?.toUpperCase() ?? '' |
| 37 | + const remainingCharacters = word.substring(1) |
| 38 | + |
| 39 | + return firstCharacter + remainingCharacters |
| 40 | + } |
| 41 | + |
| 42 | + // Keep the original name for backward compatibility |
| 43 | + const camelize = toPascalCase |
| 44 | + |
| 45 | + return { |
| 46 | + camelize, |
| 47 | + toPascalCase, |
| 48 | + capitalizeFirstLetter, |
| 49 | + } |
| 50 | +} |
0 commit comments