-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
38 lines (36 loc) · 848 Bytes
/
stack.js
File metadata and controls
38 lines (36 loc) · 848 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
class Stack {
constructor() {
this.item = []; // initialize with an empty array
}
is_empty() {
return this.item.length === 0;
}
push(n) {
this.item.push(n);
}
pop() {
if (!this.is_empty()) {
console.log(this.item.pop());
} else {
alert("No element is there in the stack");
}
}
peek() {
if (!this.is_empty()) {
console.log(this.item[this.item.length - 1]);
} else {
alert("No element in the stack to peek");
}
}
size() {
return console.log(this.item.length);
}
}
const st = new Stack();
st.push(10);
st.push(20);
st.peek(); // output: 20
st.size(); // output: 2
st.pop(); // output: 20
st.pop(); // output: 10
st.pop(); // alert: no element is there in the stack