-
Notifications
You must be signed in to change notification settings - Fork 203
/
case.ts
95 lines (81 loc) · 2.14 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
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
95
import mapObject from 'map-obj';
import { camelCase } from 'camel-case';
import { pascalCase } from 'pascal-case';
import { snakeCase } from 'snake-case';
function isLastCharNumber(key: string) {
return /^\d$/.test(key[key.length - 1]);
}
function splitLastChar(key: string) {
return `${key.slice(0, key.length - 1)}_${key.slice(
key.length - 1,
key.length
)}`;
}
function snakecase(str: string) {
const matches = str.match(/\d+/g);
if (!matches) {
return snakeCase(str);
}
let modifiedStr = str;
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
const mathIndex = modifiedStr.indexOf(match);
modifiedStr = `${modifiedStr.slice(0, mathIndex)}_${modifiedStr.slice(
mathIndex,
modifiedStr.length
)}`;
}
return snakeCase(modifiedStr);
}
function snakecaseKeys(
obj: Record<string, any>,
options: { deep?: boolean } = {}
) {
return mapObject(obj, (key, val) => [snakecase(key), val], options);
}
function snakecaseKeysDeep(obj: Record<string, any>) {
return snakecaseKeys(obj, { deep: true });
}
function camelcase(str: string) {
const parts = str.split('_');
const modifiedStr = parts.reduce((acc, part) => {
if (acc === '') return part;
if (/^\d+/.test(part)) {
return acc + part;
}
return `${acc}_${part}`;
}, '');
return camelCase(modifiedStr);
}
function camelcaseKeys(
obj: Record<string, any>,
options: { deep?: boolean } = {}
) {
return mapObject(obj, (key, val) => [camelcase(key), val], options);
}
function camelcaseKeysDeep(obj: Record<string, any>) {
return camelcaseKeys(obj, { deep: true });
}
function pascalcase(str: string) {
return pascalCase(isLastCharNumber(str) ? splitLastChar(str) : str);
}
function pascalcaseKeys(
obj: Record<string, any>,
options: { deep?: boolean } = {}
) {
return mapObject(obj, (key, val) => [pascalcase(key), val], options);
}
function pascalcaseKeysDeep(obj: Record<string, any>) {
return pascalcaseKeys(obj, { deep: true });
}
export {
snakecase,
snakecaseKeys,
snakecaseKeysDeep,
camelcase,
camelcaseKeys,
camelcaseKeysDeep,
pascalcase,
pascalcaseKeys,
pascalcaseKeysDeep,
};