-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
74 lines (61 loc) · 1.75 KB
/
Copy pathstack.js
File metadata and controls
74 lines (61 loc) · 1.75 KB
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
class Stack {
// Private variables
#items
// Constructor, Array is used to implement a Stack
constructor(){
this.#items = []
}
// add item to the begining of the items array and return its index
push (item){
return this.#items.push(item)
}
// delete the item from the begining of the stack and return its value (Last in First Out)
pop (){
if (!this.isEmpty()){
return this.#items.pop()
}
return null
}
// return the top most item from stack but does not delete it
peek (){
if (!this.isEmpty())
return this.#items[ (this.#items.length) - 1]
return null
}
// return true if the stack be empty
isEmpty(){
if (this.#items.length === 0)
return true
return false
}
// print out all items in the stack
printStack() {
if (!this.isEmpty()){
this.#items.forEach(item => console.log(item))
}
else
console.log("Stack is Empty")
}
}
// // Create an object from Stack
// const stack = new Stack()
// console.log("--------------push----------------")
// // testing push function
// console.log(stack.push("Fruit"))
// console.log(stack.push("Car"))
// console.log(stack.push("laptop"))
// console.log(stack.push("Desk"))
// console.log(stack.push("Monitor"))
// // print the Stack
// stack.printStack()
// console.log("----------------pop--------------")
// // testing pop function
// stack.pop()
// stack.pop()
// // print the Stack
// stack.printStack()
// console.log("-----------------peek-------------")
// // testing peek function
// console.log(stack.peek())
// console.log("---------------isEmpty---------------")
// console.log(stack.isEmpty())