Skip to content

Commit fe689b3

Browse files
committed
Added Stack implementation in JavaScript
1 parent 652ee3d commit fe689b3

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

‎DataStructures/Stacks/Stack.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//Language: Javascript
2+
//Author: Uddesh Jain
3+
//Github: https://github.com/UddeshJain
4+
class Stack {
5+
constructor() {
6+
this._storage = {}
7+
this._length = 0
8+
}
9+
/*
10+
* Adds a new value in the end of the Stack
11+
* @param {*} value - the value to push
12+
*/
13+
push(value) {
14+
if (value) {
15+
this._storage[this._length] = value
16+
this._length++
17+
}
18+
}
19+
/*
20+
* Removes the value at the end of stack and returns it
21+
* @return {*} the last and newest value in the Stack
22+
*/
23+
pop() {
24+
if (this._length) {
25+
const lastValue = this._storage[this._length - 1]
26+
this._storage[this._length - 1] = undefined
27+
this._length--
28+
return lastValue
29+
}
30+
}
31+
/*
32+
* Returns the value at the end of Stack without removing it
33+
* @return {*} the last and newest value in Stack
34+
*/
35+
peek() {
36+
return lastValue = this._storage[this._storage - 1]
37+
}
38+
}
39+
40+
const myStack = new Stack() // Creates new instance
41+
myStack.push('First') // Adds the value to the Stack
42+
myStack.pop() // Removes the last value in Stack
43+
myStack.peek() // Returns the last value in Stack

0 commit comments

Comments
 (0)