-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstack.js
More file actions
53 lines (38 loc) · 854 Bytes
/
stack.js
File metadata and controls
53 lines (38 loc) · 854 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
46
47
48
49
50
51
52
53
class Stack {
constructor(length) {
this._items = new Array(length);
this._index = 0;
}
get length() {
return this._index;
}
get isEmpty() {
return this._index === 0;
}
get isFull() {
return this._index === this._items.length;
}
peek() {
if (this.isEmpty) {
throw new RangeError("Cannot peek at an empty stack!");
}
return this._items[this._index - 1];
}
pop() {
if (this.isEmpty) {
throw new RangeError("Cannot pop from an empty stack!");
}
this._index -= 1;
const item = this._items[this._index];
this._items[this._index] = undefined;
return item;
}
push(item) {
if (this.isFull) {
throw new RangeError("Cannot push into a full stack!");
}
this._items[this._index] = item;
this._index += 1;
}
}
module.exports = Stack;