|
| 1 | +/** |
| 2 | + * String formatting utilities. |
| 3 | + */ |
| 4 | + |
| 5 | +/** |
| 6 | + * Truncate string to maximum length. |
| 7 | + * |
| 8 | + * @param value - String to truncate |
| 9 | + * @param maxLength - Maximum length (including suffix) |
| 10 | + * @param suffix - Suffix to add if truncated |
| 11 | + * @param preserveWords - Whether to preserve word boundaries |
| 12 | + * @returns Truncated string |
| 13 | + */ |
| 14 | +export function truncateString( |
| 15 | + value: string, |
| 16 | + maxLength: number, |
| 17 | + suffix: string = "...", |
| 18 | + preserveWords: boolean = true |
| 19 | +): string { |
| 20 | + if (value.length <= maxLength) { |
| 21 | + return value; |
| 22 | + } |
| 23 | + |
| 24 | + if (preserveWords) { |
| 25 | + const truncated = value.substring(0, maxLength - suffix.length); |
| 26 | + const lastSpace = truncated.lastIndexOf(" "); |
| 27 | + if (lastSpace > maxLength * 0.5) { |
| 28 | + return truncated.substring(0, lastSpace) + suffix; |
| 29 | + } |
| 30 | + return truncated + suffix; |
| 31 | + } |
| 32 | + |
| 33 | + return value.substring(0, maxLength - suffix.length) + suffix; |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Convert string to URL-friendly slug. |
| 38 | + * |
| 39 | + * @param value - String to slugify |
| 40 | + * @param separator - Word separator character |
| 41 | + * @returns Slugified string |
| 42 | + */ |
| 43 | +export function slugify(value: string, separator: string = "-"): string { |
| 44 | + return value |
| 45 | + .toLowerCase() |
| 46 | + .trim() |
| 47 | + .replace(/[\s_]+/g, separator) |
| 48 | + .replace(/[^\w\-]+/g, "") |
| 49 | + .replace(new RegExp(`${separator}+`, "g"), separator) |
| 50 | + .replace(new RegExp(`^${separator}|${separator}$`, "g"), ""); |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Convert camelCase to snake_case. |
| 55 | + * |
| 56 | + * @param value - CamelCase string |
| 57 | + * @returns snake_case string |
| 58 | + */ |
| 59 | +export function camelToSnake(value: string): string { |
| 60 | + return value |
| 61 | + .replace(/([A-Z])/g, "_$1") |
| 62 | + .toLowerCase() |
| 63 | + .replace(/^_/, ""); |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Convert snake_case to camelCase. |
| 68 | + * |
| 69 | + * @param value - snake_case string |
| 70 | + * @param capitalizeFirst - Whether to capitalize first letter (PascalCase) |
| 71 | + * @returns camelCase or PascalCase string |
| 72 | + */ |
| 73 | +export function snakeToCamel( |
| 74 | + value: string, |
| 75 | + capitalizeFirst: boolean = false |
| 76 | +): string { |
| 77 | + const components = value.split("_"); |
| 78 | + const first = capitalizeFirst |
| 79 | + ? components[0].charAt(0).toUpperCase() + components[0].slice(1) |
| 80 | + : components[0]; |
| 81 | + const rest = components |
| 82 | + .slice(1) |
| 83 | + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)); |
| 84 | + return first + rest.join(""); |
| 85 | +} |
0 commit comments