-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathstack.ts
More file actions
45 lines (36 loc) · 769 Bytes
/
stack.ts
File metadata and controls
45 lines (36 loc) · 769 Bytes
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
// src/04-stack/stack.ts
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
isEmpty(): boolean {
return this.items.length === 0;
}
get size(): number {
return this.items.length;
}
clear(): void {
this.items = [];
}
toString(): string {
if (this.isEmpty()) {
return 'Empty Stack';
} else {
return this.items.map(item => {
if (typeof item === 'object' && item !== null) {
return JSON.stringify(item);
} else {
return item.toString();
}
}).join(', ');
}
}
}
export default Stack;