-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse_name.ts
98 lines (90 loc) · 1.71 KB
/
parse_name.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
let ctx = "";
let pos = 0;
let len = 0;
let results: (string | number | null)[] = [];
type NextHandle = () => NextHandle | null;
function array(): NextHandle | null {
let isArray = true;
for (let i = pos; i <= len; i++) {
switch (ctx.charAt(i)) {
case "":
return null;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": {
break;
}
case "]": {
const token = ctx.slice(pos, i);
pos = i + 1;
if (token === "") {
results.push(null);
} else {
results.push(isArray ? +token : token);
}
return arrayOrObject;
}
default: {
isArray = false;
}
}
}
return null;
}
function arrayOrObject() {
if (pos >= len) {
return null;
}
if (ctx.charAt(pos) === "[") {
pos++;
return array;
}
if (ctx.charAt(pos) === ".") {
pos++;
return object;
}
throw new Error("syntax error");
}
function object(): NextHandle | null {
for (let i = pos; i <= len; i++) {
switch (ctx.charAt(i)) {
case "[": {
results.push(ctx.slice(pos, i));
pos = i + 1;
return array;
}
case ".": {
if (pos !== i) {
results.push(ctx.slice(pos, i));
}
pos = i + 1;
return object;
}
}
}
if (pos < len) {
results.push(ctx.slice(pos));
}
return null;
}
export function parseName(name: string): (string | number | null)[] {
if (name === "") {
return [""];
}
results = [];
pos = 0;
len = name.length;
ctx = name;
let next = object();
while (next) {
next = next();
}
return results;
}