-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.ts
57 lines (43 loc) · 1.1 KB
/
list.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
export default class List {
private memory: any[];
private length: number;
constructor() {
this.memory = [];
this.length = 0;
}
get(address: number): any {
return this.memory[address];
}
push(value: any): void {
this.memory[this.length] = value;
this.length++;
}
pop(): any {
if (this.length === 0) return;
const lastAddress = this.length - 1;
const lastValue = this.memory[lastAddress];
delete this.memory[lastAddress];
this.length--;
return lastValue;
}
unshift(value: any): void {
let previous = value;
for (let address = 0; address < this.length; address++) {
let current = this.memory[address];
this.memory[address] = previous;
previous = current;
}
this.memory[this.length] = previous;
this.length++;
}
shift(): any {
if (this.length === 0) return;
const firstValue = this.memory[0];
for (let address = 0; address < this.length; address++) {
this.memory[address] = this.memory[address + 1];
}
delete this.memory[this.length - 1];
this.length--;
return firstValue;
}
}