/
stack.ts
57 lines (48 loc) · 998 Bytes
/
stack.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
import { ObjectType } from '../model/objectType';
export class Stack<T> {
private _stack: ObjectType<T>;
private _count: number;
constructor() {
this._stack = {};
this._count = 0;
}
get isEmpty(): boolean {
return this.size === 0;
}
get size(): number {
return this._count;
}
push(value: T) {
this._stack[this._count] = value;
this._count++;
}
pop(): T {
if (this.isEmpty) {
return undefined;
}
this._count--;
const value = this._stack[this._count];
delete this._stack[this._count];
return value;
}
peek(): T {
if (this.isEmpty) {
return undefined;
}
return this._stack[this._count - 1];
}
clear(): void {
this._stack = {};
this._count = 0;
}
print(): string {
if (this.isEmpty) {
return '';
}
let values = [];
for (let i = 0; i < this._count; i++) {
values.unshift((this._stack[i] as any).toString());
}
return values.join(' -> ');
}
}