-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
107 lines (86 loc) · 2.37 KB
/
index.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
96
97
98
99
100
101
102
103
104
105
106
107
export const JSONC = (() => {
class JsoncProcessor {
toJSON(content: string): string {
const length = content.length;
let inBlockComment = false;
let inString = false;
let skipChar = false;
let result = '';
for (let i = 0; i < length; i++) {
const char = content[i];
if (skipChar) {
skipChar = false;
continue;
}
if (inBlockComment) {
if (char === '*' && content[i + 1] === '/') {
inBlockComment = false;
skipChar = true;
}
continue;
}
if (inString) {
if (char === '"' && content[i - 1] !== '\\') {
inString = false;
}
result += char;
continue;
}
if (char === '"') {
inString = true;
result += char;
continue;
}
if (char === '/' && content[i + 1] === '*') {
inBlockComment = true;
skipChar = true;
continue;
}
if (char === '/' && content[i + 1] === '/') {
while (i < length && content[i] !== '\n') {
i++;
}
continue;
}
result += char;
}
return result;
}
parse<T = unknown>(
text: string,
reviver?: (this: unknown, key: string, value: unknown) => unknown
): T {
const cleanContent = this.toJSON(text);
return JSON.parse(cleanContent, reviver);
}
stringify(
value: unknown,
replacer?: (this: unknown, key: string, value: unknown) => unknown,
space?: string | number
): string;
stringify(
value: unknown,
replacer?: (number | string)[] | null,
space?: string | number
): string;
stringify(
value: unknown,
replacer?:
| ((this: unknown, key: string, value: unknown) => unknown)
| (number | string)[]
| null,
space?: string | number
): string {
const source = typeof value === 'string' ? this.parse(value) : value;
if (typeof replacer === 'function') {
return JSON.stringify(source, replacer, space);
}
return JSON.stringify(source, replacer, space);
}
minify(content: string): string {
const parsedConfig = this.parse(content);
return JSON.stringify(parsedConfig, null, 0);
}
}
return new JsoncProcessor();
})();