-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcast.ts
More file actions
115 lines (87 loc) · 2.12 KB
/
cast.ts
File metadata and controls
115 lines (87 loc) · 2.12 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const isBooleanString = (value: string): value is 'true' | 'false' => {
return value === 'true' || value === 'false';
};
const isNull = (value: string | null): value is 'null' | null => {
return value === 'null' || value === null;
};
const isJsonStructure = (value: string): boolean => {
const trimmed = value.trim();
return (
(trimmed.startsWith('{') && trimmed.endsWith('}')) ||
(trimmed.startsWith('[') && trimmed.endsWith(']'))
);
};
const isNumericString = (value: string): boolean => {
const trimmed = value.trim();
if (!trimmed) {
return false;
}
const parsed = Number(trimmed);
return Number.isFinite(parsed);
};
const parseNumber = (value: string): number | string => {
return isNumericString(value) ? Number(value) : value;
};
const parseBoolean = (value: string): boolean | string => {
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
return value;
};
const parseNull = (value: string | null): null | string => {
return isNull(value) ? null : value;
};
const parseJson = (value: string): unknown => {
if (!isJsonStructure(value)) {
return value;
}
try {
return JSON.parse(value);
} catch {
return value;
}
};
export type CastType = 'auto' | 'string' | 'number' | 'boolean' | 'null' | 'json';
const parseAuto = (value: string): unknown => {
if (isBooleanString(value)) {
return value === 'true';
}
if (isNull(value)) {
return null;
}
if (isNumericString(value)) {
return Number(value);
}
if (isJsonStructure(value)) {
try {
return JSON.parse(value);
} catch {
return value;
}
}
return value;
};
export const cast = (value: string | null, type: CastType = 'auto'): unknown => {
if (value === null) {
return null;
}
switch (type) {
case 'string':
return value;
case 'number':
return parseNumber(value);
case 'boolean':
return parseBoolean(value);
case 'null':
return parseNull(value);
case 'json':
return parseJson(value);
case 'auto':
default:
return parseAuto(value);
}
};
export default cast;