finish embed components
This commit is contained in:
37
helpers/convert-object-property-case.test.ts
Normal file
37
helpers/convert-object-property-case.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type {
|
||||
CamelCasedPropertiesDeep,
|
||||
SnakeCasedPropertiesDeep,
|
||||
} from "type-fest"
|
||||
import { camelCaseDeep, snakeCaseDeep } from "./convert-object-property-case"
|
||||
|
||||
test("camelCaseDeep", () => {
|
||||
const input = {
|
||||
some_prop: {
|
||||
some_deep_prop: "some_deep_value",
|
||||
},
|
||||
someOtherProp: "someOtherValue",
|
||||
}
|
||||
|
||||
expect(camelCaseDeep(input)).toEqual<CamelCasedPropertiesDeep<typeof input>>({
|
||||
someProp: {
|
||||
someDeepProp: "some_deep_value",
|
||||
},
|
||||
someOtherProp: "someOtherValue",
|
||||
})
|
||||
})
|
||||
|
||||
test("snakeCaseDeep", () => {
|
||||
const input = {
|
||||
someProp: {
|
||||
someDeepProp: "someDeepValue",
|
||||
},
|
||||
some_other_prop: "someOtherValue",
|
||||
}
|
||||
|
||||
expect(snakeCaseDeep(input)).toEqual<SnakeCasedPropertiesDeep<typeof input>>({
|
||||
some_prop: {
|
||||
some_deep_prop: "someDeepValue",
|
||||
},
|
||||
some_other_prop: "someOtherValue",
|
||||
})
|
||||
})
|
||||
34
helpers/convert-object-property-case.ts
Normal file
34
helpers/convert-object-property-case.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { camelCase, isObject, snakeCase } from "lodash-es"
|
||||
import type {
|
||||
CamelCasedPropertiesDeep,
|
||||
SnakeCasedPropertiesDeep,
|
||||
} from "type-fest"
|
||||
|
||||
function convertKeyCaseDeep<Input, Output>(
|
||||
input: Input,
|
||||
convertKey: (key: string) => string,
|
||||
): Output {
|
||||
if (!isObject(input)) {
|
||||
return input as unknown as Output
|
||||
}
|
||||
|
||||
if (Array.isArray(input)) {
|
||||
return input.map((item) =>
|
||||
convertKeyCaseDeep(item, convertKey),
|
||||
) as unknown as Output
|
||||
}
|
||||
|
||||
const output: any = {}
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
output[convertKey(key)] = convertKeyCaseDeep(value, convertKey)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
export function camelCaseDeep<T>(input: T): CamelCasedPropertiesDeep<T> {
|
||||
return convertKeyCaseDeep(input, camelCase)
|
||||
}
|
||||
|
||||
export function snakeCaseDeep<T>(input: T): SnakeCasedPropertiesDeep<T> {
|
||||
return convertKeyCaseDeep(input, snakeCase)
|
||||
}
|
||||
Reference in New Issue
Block a user