-
Notifications
You must be signed in to change notification settings - Fork 0
/
NestedInteger.ts
55 lines (49 loc) · 1.3 KB
/
NestedInteger.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
import { NestedIntegerType } from "./NestedIntegerType.ts";
export class NestedInteger {
[k: number]: NestedInteger
length = 0;
valueOf() {
return this.#value;
}
[Symbol.iterator]() {
return Array.prototype[Symbol.iterator].call(this);
}
#value: number;
#type: NestedIntegerType;
constructor(value?: number) {
if (typeof value === "number") {
this.#value = value;
this.#type = NestedIntegerType.integer;
} else {
this.#type = NestedIntegerType.array;
this.#value = 0;
}
}
isInteger(): boolean {
return this.#type === NestedIntegerType.integer;
}
getInteger(): number | null {
if (this.isInteger()) {
return this.#value;
} else {
return null;
}
}
setInteger(value: number) {
if (this.isInteger()) {
this.#value = value;
} else {
throw Error("not integer can not set");
}
}
add(elem: NestedInteger) {
if (this.#type === NestedIntegerType.array) {
Array.prototype.push.call(this, elem);
} else {
throw Error("not array can not add");
}
}
getList(): NestedInteger[] {
return Array.from(this);
}
}