-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathObject$tring.js
40 lines (40 loc) · 1.52 KB
/
Object$tring.js
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
export class Object$tring {
s;
strVal;
objVal;
arrVal;
constructor(s) {
this.s = s;
}
async parse() {
const s = this.s;
const trim = s.trim();
const firstChar = trim[0];
const firstOpenBracePos = firstChar === '{' ? 0 : -1;
const firstOpenBracketPos = firstChar === '[' ? 0 : -1;
if (firstOpenBracePos === -1 && firstOpenBracketPos === -1) {
this.strVal = trim;
return;
}
const lastCloseBracePos = trim.lastIndexOf('}');
const lastCloseBracketPos = trim.lastIndexOf(']');
if (lastCloseBracePos === -1 && lastCloseBracketPos === -1) {
this.strVal = trim;
return;
}
if ((firstOpenBracketPos === -1 || firstOpenBracePos < firstOpenBracketPos) &&
(lastCloseBracketPos === -1 || lastCloseBracePos > lastCloseBracketPos)) {
this.strVal = trim.substring(lastCloseBracePos + 1).trim();
const jsonString = trim.substring(firstOpenBracePos, lastCloseBracePos + 1);
this.objVal = JSON.parse(jsonString);
return;
}
if ((firstOpenBracePos === -1 || firstOpenBracketPos < firstOpenBracePos) &&
(lastCloseBracePos === -1 || lastCloseBracketPos > lastCloseBracePos)) {
this.strVal = trim.substring(lastCloseBracketPos + 1).trim();
this.arrVal = JSON.parse(trim.substring(firstOpenBracketPos, lastCloseBracketPos + 1));
return;
}
this.strVal = trim;
}
}