-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add snake_case and camelCase conversions
- Loading branch information
Showing
2 changed files
with
37 additions
and
3 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
/** | ||
* Converts object keys from camelCase to snake_case | ||
*/ | ||
export function toSnakeCase<T extends object>(obj: T): Record<string, unknown> { | ||
return Object.entries(obj).reduce( | ||
(acc, [key, value]) => { | ||
// Convert camelCase to snake_case | ||
const snakeKey = key.replace( | ||
/[A-Z]/g, | ||
(letter) => `_${letter.toLowerCase()}`, | ||
); | ||
acc[snakeKey] = value; | ||
return acc; | ||
}, | ||
{} as Record<string, unknown>, | ||
); | ||
} | ||
|
||
/** | ||
* Converts object keys from snake_case to camelCase | ||
*/ | ||
export function toCamelCase<T extends object>(obj: T): Record<string, unknown> { | ||
return Object.entries(obj).reduce( | ||
(acc, [key, value]) => { | ||
// Convert snake_case to camelCase | ||
const camelKey = key.replace(/_([a-z])/g, (_, letter) => | ||
letter.toUpperCase(), | ||
); | ||
acc[camelKey] = value; | ||
return acc; | ||
}, | ||
{} as Record<string, unknown>, | ||
); | ||
} |