-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.js
90 lines (80 loc) · 1.88 KB
/
stack.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Stacks
*
* The stack data structure is precisely what it sounds like: a stack of data. In
* certain types of problems, it can be favourable to store data in a stack rather
* than an array.
*
* A stack uses LIFO (last-in first out) ordering. That is, as in a stack of dinner
* plates, the most recent item added to the stack is the first item to be removed.
*
* The most common usage of stacks is places where you have one process adding
* items to the stack and another process removing them from the end–
* prioritizing items added most recently.
*
* Usually in Javascript we don't need to create an abstract stack data structure
* and can instead use a simple array object.
*
* We can achieve the LIFO properties with the .push() and .pop() methods.
*
* push(4)
* ↙
* [1, 2, 3]
* ↘
* pop(4)
*
* Key Operations:
*
* pop: O(1)
* push: O(1)
* peek: O(1)
*/
class Stack {
/**
* @constructor
*
* We use an array to store our frames. We're also going to track the length.
*/
constructor() {
this.items = [];
this.length = 0;
}
/**
* push()
*
* Simple method to push a frame onto our stack. We use the Array.push() method
* and increment our length.
*
* @param {*} value the value to push
* @return {void}
*/
push(value) {
this.length += 1;
this.items.push(value);
}
/**
* pop()
*
* Use the Array.pop() method to pop the top frame from our stack. We also decrement
* our length by 1.
*
* @return {*} the top frame from our stack
*/
pop() {
if (this.length === 0) return null;
this.length -= 1;
return this.items.pop();
}
/**
* peek()
*
* Similar to pop(), except we do not remove the frame, we simply 'peek' at its
* value
*
* @return {*} returns the top frame
*/
peek() {
return this.items[this.length - 1];
}
}
export default Stack;