forked from TheAlgorithms/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.ts
More file actions
76 lines (67 loc) · 1.92 KB
/
stack.ts
File metadata and controls
76 lines (67 loc) · 1.92 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* Stack data-structure. It's work is based on the LIFO method (last-IN-first-OUT).
* It means that elements added to the stack are placed on the top and only the
* last element (from the top) can be reached. After we get access to the last
* element, it pops from the stack.
* This is a class-based implementation of a Stack.
*/
export class Stack<T> {
private stack: T[] = [];
private limit: number;
/**
* constructor of the stack, can set a limit, if not provided there is no limit to the stack.
* @param {number} [limit=Number.MAX_VALUE] the limit of the stack
*/
constructor(limit: number = Number.MAX_VALUE) {
this.limit = limit;
}
/**
* @function push
* @description - adds a new element to the stack
* @param {T} value - the new value to add
*/
push(value: T) {
if (this.length() + 1 > this.limit) {
throw new Error('Stack Overflow');
}
this.stack.push(value);
}
/**
* @function pop
* @description - remove an element from the top
* @throws will throw an error if the stack is empty
* @return {T} removed element
*/
pop(): T {
if (this.length() !== 0) {
return this.stack.pop() as T;
}
throw new Error('Stack Underflow');
}
/**
* @function length
* @description - number of elements in the stack
* @return {number} the number of elements in the stack
*/
length(): number {
return this.stack.length;
}
/**
* @function isEmpty
* @description - check if the stack is empty
* @return {boolean} returns true if the stack is empty, otherwise false
*/
isEmpty(): boolean {
return this.length() === 0;
}
/**
* @function top
* @description - return the last element in the stack without removing it
* @return {T | null} return the last element or null if the stack is empty
*/
top(): T | null {
if (this.length() !== 0) {
return this.stack[this.length() - 1];
}
return null;
}
}