/
stack.js
59 lines (51 loc) · 923 Bytes
/
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
/**
* Stack - LIFO, like a stack of dishes
*
* NOTE: This stack is implemented with an array as its underlying data structure.
*
* Methods and properties:
*
* - push: Constant — O(1)
* - pop: Constant — O(1)
* - peek: Constant — O(1)
* - isEmpty: Constant — O(1)
* - size: Constant — O(1)
* - enumerate: Linear - O(n)
* - clear: Constant - O(1)
*/
export class Stack {
constructor() {
this.items = []
this.length = 0
}
push(val) {
this.items.unshift(val)
this.length++
return val
}
pop() {
if (this.length) {
this.length--
return this.items.shift()
} else {
return null
}
}
peek() {
return this.items[0] || null
}
isEmpty() {
return this.length === 0
}
size() {
return this.length
}
enumerate() {
return this.items
}
clear() {
this.length = 0
this.items = []
return this.items
}
}