Skip to content

Commit e061178

Browse files
Makso83itsvinayakruppysuppy
authored
new stack implementation (ES6) fixes: #{246} (TheAlgorithms#247)
* new stack implementation (ES6) fixes: #{246} * Update Data-Structures/Stack/StackES6.js Co-authored-by: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> * Update StackES6.js Co-authored-by: vinayak <itssvinayak@gmail.com> Co-authored-by: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com>
1 parent c1489ec commit e061178

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Data-Structures/Stack/StackES6.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/* Stack data-structure. It's work is based on the LIFO method (last-IN-first-OUT).
2+
* It means that elements added to the stack are placed on the top and only the
3+
* last element (from the top) can be reached. After we get access to the last
4+
* element, he pops from the stack.
5+
* This is a class-based implementation of a Stack. It provides functions
6+
* 'push' - to add an element, 'pop' - to remove an element from the top.
7+
* Also it implements 'length', 'last' and 'isEmpty' properties and
8+
* static isStack method to check is an object the instance of Stack class.
9+
*/
10+
11+
// Class declaration
12+
class Stack {
13+
constructor () {
14+
this.stack = []
15+
this.top = 0
16+
}
17+
18+
// Adds a value to the end of the Stack
19+
push (newValue) {
20+
this.stack.push(newValue)
21+
this.top += 1
22+
}
23+
24+
// Returns and removes the last element of the Stack
25+
pop () {
26+
if (this.top !== 0) {
27+
this.top -= 1
28+
return this.stack.pop()
29+
}
30+
throw new Error('Stack Underflow')
31+
}
32+
33+
// Returns the number of elements in the Stack
34+
get length () {
35+
return this.top
36+
}
37+
38+
// Returns true if stack is empty, false otherwise
39+
get isEmpty () {
40+
return this.top === 0
41+
}
42+
43+
// Returns the last element without removing it
44+
get last () {
45+
if (this.top !== 0) {
46+
return this.stack[this.stack.length - 1]
47+
}
48+
return null
49+
}
50+
51+
// Checks if an object is the instance os the Stack class
52+
static isStack (el) {
53+
return el instanceof Stack
54+
}
55+
}
56+
const newStack = new Stack()
57+
console.log('Is it a Stack?,', Stack.isStack(newStack))
58+
console.log('Is stack empty? ', newStack.isEmpty)
59+
newStack.push('Hello world')
60+
newStack.push(42)
61+
newStack.push({ a: 6, b: 7 })
62+
console.log('The length of stack is ', newStack.length)
63+
console.log('Is stack empty? ', newStack.isEmpty)
64+
console.log('Give me the last one ', newStack.last)
65+
console.log('Pop the latest ', newStack.pop())
66+
console.log('Pop the latest ', newStack.pop())
67+
console.log('Pop the latest ', newStack.pop())
68+
console.log('Is stack empty? ', newStack.isEmpty)

0 commit comments

Comments
 (0)