-
Notifications
You must be signed in to change notification settings - Fork 0
/
01383-hard-camelize.ts
94 lines (84 loc) · 2.23 KB
/
01383-hard-camelize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// ============= Test Cases =============
import type { Equal, Expect } from "./test-utils";
type cases = [
Expect<
Equal<
Camelize<{
some_prop: string;
prop: { another_prop: string };
array: [
{ snake_case: string },
{ another_element: { yet_another_prop: string } },
{ yet_another_element: string }
];
}>,
{
someProp: string;
prop: { anotherProp: string };
array: [
{ snakeCase: string },
{ anotherElement: { yetAnotherProp: string } },
{ yetAnotherElement: string }
];
}
>
>
];
// ============= Your Code Here =============
type Camelize<T extends Record<string, unknown>> = {
[Key in keyof T as CamelizeKey<Key>]: T[Key] extends Record<string, unknown>
? Camelize<T[Key]>
: T[Key] extends unknown[]
? CamelizeArr<T[Key]>
: T[Key];
};
type CamelizeKey<T extends string | number | symbol> =
T extends `${infer First}_${infer Rest}`
? CamelizeKey<`${First}${Capitalize<Rest>}`>
: T;
type CamelizeArr<T extends unknown[]> = T extends [
infer First extends Record<string, unknown>,
...infer Rest extends Record<string, unknown>[]
]
? [Camelize<First>, ...CamelizeArr<Rest>]
: T;
type CamelizeObjAttrs<T extends Record<string, unknown>> = {
[Key in keyof T as CamelizeKey<Key>]: T[Key];
};
type test1 = CamelizeKey<"some_prop">;
type test2 = CamelizeKey<"some">;
type test3 = CamelizeKey<"some_">;
type test4 = CamelizeObjAttrs<{
some_prop: string;
some_other_prop: number;
}>;
type test5 = Camelize<{
some_prop: string;
prop: { another_prop: string };
array: [
{ snake_case: string },
{ another_element: { yet_another_prop: string } },
{ yet_another_element: string }
];
}>;
const Test5: test5 = {
someProp: "hi",
prop: { anotherProp: "hi" },
array: [
{ snakeCase: "hi" },
{ anotherElement: { yetAnotherProp: "hi" } },
{ yetAnotherElement: "hi" },
],
};
type test6 = CamelizeArr<
[
{ snake_case: "hi" },
{ another_element: { yet_another_prop: "hi" } },
{ yet_another_element: "hi" }
]
>;
const Test6: test6 = [
{ snakeCase: "hi" },
{ anotherElement: { yetAnotherProp: "hi" } },
{ yetAnotherElement: "hi" },
];