-
Notifications
You must be signed in to change notification settings - Fork 349
/
case.ts
52 lines (45 loc) · 1.63 KB
/
case.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
import { camelCase as camelCaseAnything } from "case-anything";
import { Options } from "./options";
/** Converts `key` to TS/JS camel-case idiom, unless overridden not to. */
export function maybeSnakeToCamel(key: string, options: Pick<Options, "snakeToCamel">): string {
if (options.snakeToCamel.includes("keys") && key.includes("_")) {
return snakeToCamel(key);
} else {
return key;
}
}
export function snakeToCamel(s: string): string {
const hasLowerCase = !!s.match(/[a-z]/);
return s
.split("_")
.map((word, i) => {
// If the word is already mixed case, leave the existing case as-is
word = hasLowerCase ? word : word.toLowerCase();
return i === 0 ? word : capitalize(word);
})
.join("");
}
export function camelToSnake(s: string): string {
return (
s
// any number or little-char -> big char
.replace(/[a-z0-9]([A-Z])/g, (m) => m[0] + "_" + m[1])
// any multiple big char -> next word
.replace(/[A-Z]([A-Z][a-z])/g, (m) => m[0] + "_" + m.substring(1))
.toUpperCase()
);
}
export function capitalize(s: string): string {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
export function uncapitalize(s: string): string {
return s.substring(0, 1).toLowerCase() + s.substring(1);
}
/* This function uses the exact same semantics found inside the grpc
* nodejs library. Camel case splitting must be done by word i.e
* GetAPIValue must become getApiValue (notice the API becomes Api).
* This needs to be followed otherwise it will not succeed in the grpc nodejs module.
*/
export function camelCaseGrpc(s: string): string {
return camelCaseAnything(s);
}