-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmini-parser.ts
63 lines (60 loc) · 1.62 KB
/
mini-parser.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
export class NestedInteger {
declare value: number | (number | NestedInteger)[];
constructor(value?: number) {
if (value !== undefined) {
this.value = value;
}
}
setInteger(value: number) {
this.value = value;
}
add(elem: NestedInteger) {
Array.isArray(this.value) || (this.value = []);
this.value.push(elem);
}
}
function build(head: NestedInteger, tokens: readonly string[], ref: Record<"i", number>): NestedInteger {
if (ref.i < tokens.length) {
let token = tokens[ref.i];
if (token === "[") {
++ref.i;
while (tokens[ref.i] !== "]") {
head.add(build(new NestedInteger(), tokens, ref));
++ref.i;
}
} else {
// numbers
head.setInteger(Number(token));
}
}
return head;
}
export function deserialize(s: string): NestedInteger {
let tokens: string[] = [];
let token = "";
for (let c of s) {
if (c === "[") {
tokens.push(c);
} else if (c === "]") {
if (token !== "") {
tokens.push(token);
token = "";
}
tokens.push(c);
} else if (c === ",") {
if (token !== "") {
tokens.push(token);
token = "";
}
} else {
// digit or negative sign
token += c;
}
}
if (token !== "") {
tokens.push(token);
token = "";
}
const ref: Record<"i", number> = { i: 0 };
return build(new NestedInteger(), tokens, ref);
}