-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.ts
42 lines (35 loc) · 1018 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
/** A stack data structure, with last-in-first-out functionality. */
export default class Stack {
collection: any[] = [];
/** Adds an element to the top of the stack. */
push(element: any): void {
this.collection.push(element);
}
/** Returns the element at the top of the stack, leaving it in place. */
peek(): any {
return this.collection[this.collection.length - 1];
}
/** Removes and returns the element at the top of the stack. */
pop(): any {
return this.collection.pop();
}
/** Returns the number of elements in the stack. */
size(): number {
return this.collection.length;
}
/** Returns whether or not the stack is currently empty. */
isEmpty(): boolean {
return this.collection.length === 0;
}
/** Clears the contents of the stack. */
clear(): void {
this.collection = [];
}
/**
* Prints the stack to the console as an array with elements ordered from
* bottom to top.
*/
print(): void {
console.log(this.collection);
}
}