helpers
9 months ago
services
10 months ago
caseConversion.ts
11 months ago
translate.ts
11 months ago
caseConversion.ts
69 lines
| 1 | const isObject = (obj: unknown): boolean => |
| 2 | obj !== null && typeof obj === 'object' && !Array.isArray(obj) && !(obj instanceof Date); |
| 3 | |
| 4 | const toCamelCase = (str: string): string => |
| 5 | str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', '')); |
| 6 | |
| 7 | const toSnakeCase = (str: string): string => str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); |
| 8 | |
| 9 | const toKebabCase = (str: string): string => |
| 10 | str |
| 11 | .replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`) |
| 12 | .replace(/[\s_]+/g, '-') |
| 13 | .replace(/^-+|-+$/g, '') |
| 14 | .toLowerCase(); |
| 15 | |
| 16 | export const camelToSnakeObj = (obj: unknown): unknown => { |
| 17 | if (!isObject(obj)) return obj; |
| 18 | |
| 19 | const result: Record<string, unknown> = {}; |
| 20 | |
| 21 | for (const key in obj as Record<string, unknown>) { |
| 22 | if (Object.prototype.hasOwnProperty.call(obj, key)) { |
| 23 | const snakeKey = toSnakeCase(key); |
| 24 | const value = (obj as Record<string, unknown>)[key]; |
| 25 | |
| 26 | if (isObject(value)) { |
| 27 | result[snakeKey] = camelToSnakeObj(value); |
| 28 | } else if (Array.isArray(value)) { |
| 29 | result[snakeKey] = value.map((item) => (isObject(item) ? camelToSnakeObj(item) : item)); |
| 30 | } else { |
| 31 | result[snakeKey] = value; |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | return result; |
| 37 | }; |
| 38 | |
| 39 | export const snakeToCamelObj = <T>(obj: unknown): T => { |
| 40 | if (obj === null || typeof obj !== 'object' || obj instanceof Date) { |
| 41 | return obj as T; |
| 42 | } |
| 43 | |
| 44 | if (Array.isArray(obj)) { |
| 45 | return obj.map(snakeToCamelObj) as unknown as T; |
| 46 | } |
| 47 | |
| 48 | const result: Record<string, unknown> = {}; |
| 49 | |
| 50 | for (const key in obj as Record<string, unknown>) { |
| 51 | if (Object.prototype.hasOwnProperty.call(obj, key)) { |
| 52 | const camelKey = toCamelCase(key); |
| 53 | const value = (obj as Record<string, unknown>)[key]; |
| 54 | |
| 55 | if (isObject(value)) { |
| 56 | result[camelKey] = snakeToCamelObj(value); |
| 57 | } else if (Array.isArray(value)) { |
| 58 | result[camelKey] = value.map((item) => (isObject(item) ? snakeToCamelObj(item) : item)); |
| 59 | } else { |
| 60 | result[camelKey] = value; |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | return result as T; |
| 66 | }; |
| 67 | |
| 68 | export { toKebabCase }; |
| 69 |