Skip to content

Instantly share code, notes, and snippets.

@ShayDavidson
Created February 10, 2021 17:23
Show Gist options
  • Save ShayDavidson/c6d2fdd044f272ee5f620b67362e9262 to your computer and use it in GitHub Desktop.
Save ShayDavidson/c6d2fdd044f272ee5f620b67362e9262 to your computer and use it in GitHub Desktop.
/* eslint-disable @typescript-eslint/ban-types */
export type CamelToSnake<T extends string> = string extends T
? string
: T extends `${infer C0}${infer R}`
? `${C0 extends Uppercase<C0> ? '_' : ''}${Lowercase<C0>}${CamelToSnake<R>}`
: '';
export type SnakeToCamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}`
? `${Lowercase<P1>}${Uppercase<P2>}${SnakeToCamelCase<P3>}`
: Lowercase<S>;
export type SnakeToCamelCaseKeys<T> = {
[K in keyof T as SnakeToCamelCase<string & K>]: T[K] extends {} ? SnakeToCamelCaseKeys<T[K]> : T[K];
};
export type CamelToSnakeCaseKeys<T> = {
[K in keyof T as CamelToSnake<Extract<K, string>>]: T[K];
};
export function transformKeysNested<K extends string, T>(
object: Record<K, T>,
transform: (val: string) => string
): Record<string, T> {
return Object.keys(object).reduce((result, key) => {
if (typeof object[key] === 'object') {
return { ...result, [transform(key)]: transformKeysNested<K, T>(object[key], transform) };
} else {
return { ...result, [transform(key)]: object[key] };
}
}, {});
}
export function snakeToCamelCase(snake: string): string {
return snake.replace(/(_\w)/g, m => {
return m[1].toUpperCase();
});
}
export function snakeToCamelCaseKeys<K extends string, T>(object: Record<K, T>): SnakeToCamelCaseKeys<Record<K, T>> {
return transformKeysNested(object, snakeToCamelCase) as SnakeToCamelCaseKeys<Record<K, T>>;
}
export function camelToSnakeCase(camel: string): string {
return camel
.replace(/[\w]([A-Z])/g, m => {
return `${m[0]}_${m[1]}`;
})
.toLowerCase();
}
export function camelToSnakeCaseKeys<K extends string, T>(object: Record<K, T>): CamelToSnakeCaseKeys<Record<K, T>> {
return transformKeysNested(object, camelToSnakeCase) as CamelToSnakeCaseKeys<Record<K, T>>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment