-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathStacks.js
More file actions
40 lines (33 loc) · 647 Bytes
/
Stacks.js
File metadata and controls
40 lines (33 loc) · 647 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
// Implement a stack
class Stacks {
constructor(){
this.items = [];
}
pop(){
if(this.isEmpty()) throw "Cannot pop an empty stack";
else return this.items.pop();
}
push(item) {
this.items.push(item);
}
isEmpty(){
return this.items.length === 0;
}
peek(){
if(this.isEmpty()) throw "Empty stack";
else return this.items[this.items.length -1];
}
printStack() {
this.items.forEach( i => console.log(i))
}
}
const s = new Stacks();
s.push(2);
s.push(4);
s.push(6);
s.pop();
s.push(7);
s.push(5);
s.peek();
s.isEmpty();
s.printStack();