import type { PascalCaseOptions } from "change-case"
import { camelCase, pascalCase } from "change-case"
function changeKeysFactory<TOptions>(changeCase: (input: string, options?: TOptions) => string) {
return function changeKeys(object: unknown, depth = 1, options?: TOptions | undefined): unknown {
if (depth === 0 || !isObject(object)) {
return object
}
if (Array.isArray(object)) {
return object.map((item) => changeKeys(item, depth - 1, options))
}
const result = Object.create(Object.getPrototypeOf(object))
Object.keys(object).forEach((key) => {
const value = object[key]
const changedKey = changeCase(key, options)
const changedValue = changeKeys(value, depth - 1, options)
result[changedKey] = changedValue
})
return result
}
}
const camelCaseKeys = changeKeysFactory(camelCase)
const pascalCaseKeysExceptions = (exceptions: Record<string, string>) =>
changeKeysFactory((key: string, options?: PascalCaseOptions | undefined) =>
exceptions[key] ? exceptions[key]! : pascalCase(key, options)
)
const pascalCaseKeys = pascalCaseKeysExceptions({
zipCode: "ZIPCode",
email: "eMail",
contactId: "ContactID"
})
import type { PascalCaseOptions } from "change-case"
import { camelCase, pascalCase } from "change-case"
function changeKeysFactory<TOptions>(changeCase: (input: string, options?: TOptions) => string) {
return function changeKeys(object: unknown, depth = 1, options?: TOptions | undefined): unknown {
if (depth === 0 || !isObject(object)) {
return object
}
if (Array.isArray(object)) {
return object.map((item) => changeKeys(item, depth - 1, options))
}
const result = Object.create(Object.getPrototypeOf(object))
Object.keys(object).forEach((key) => {
const value = object[key]
const changedKey = changeCase(key, options)
const changedValue = changeKeys(value, depth - 1, options)
result[changedKey] = changedValue
})
return result
}
}
const camelCaseKeys = changeKeysFactory(camelCase)
const pascalCaseKeysExceptions = (exceptions: Record<string, string>) =>
changeKeysFactory((key: string, options?: PascalCaseOptions | undefined) =>
exceptions[key] ? exceptions[key]! : pascalCase(key, options)
)
const pascalCaseKeys = pascalCaseKeysExceptions({
zipCode: "ZIPCode",
email: "eMail",
contactId: "ContactID"
})