Last active
February 12, 2018 05:50
-
-
Save pankajladhar/77424317d56c6868dfa1b2dfd0943085 to your computer and use it in GitHub Desktop.
Implementation of Stack in javascript using Factory Approach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Stack is a linear data structure which follows a particular order in which the operations are performed. | |
The order may be LIFO(Last In First Out) or FILO(First In Last Out). | |
Mainly the following three basic operations are performed in the stack: | |
Push: Adds an item in the stack. | |
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. | |
If the stack is empty, then it is said to be an Underflow condition. | |
Peek/Top: Returns top element of stack. | |
isEmpty: Returns true if stack is empty. | |
*/ | |
const Stack = () => { | |
let arr = []; | |
return { | |
push: (data) => { | |
arr.push(data); | |
}, | |
pop: () => { | |
if (arr.length === 0) { | |
throw new Error("Stack is empty so can not pop element, Underflow") | |
} | |
else { | |
arr.pop(); | |
} | |
}, | |
peek: () => { | |
return arr[arr.length - 1] | |
}, | |
isEmpty: () => { | |
return arr.length === 0 | |
}, | |
printStack: () => { | |
return arr; | |
} | |
} | |
} | |
let stack = Stack(); | |
console.log(stack.isEmpty()) // true | |
console.log(stack.pop()) //[] Stack is empty so can not pop element, Underflow | |
stack.push(3); | |
stack.push(2); | |
stack.push(10); | |
console.log(stack.isEmpty()) // false | |
console.log(stack.printStack()); // [3, 2, 10] | |
console.log(stack.peek()) // [10] | |
stack.pop(); | |
console.log(stack.printStack()); // [3, 2] | |
console.log(stack.peek()) // [2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment