JavaScript presentation of stack data structure
This file contains 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
/** | |
* A stack is useful when we want to add data in sequential order and remove data. Based on its definition, | |
* a stack can remove only the most recently added data. | |
* | |
* stack is work on LAST IN FIRST OUT principle. | |
* stack is just like array with only capabilities of push and pop (method). | |
* [6] ----> which is last element of stack | |
* [5] | |
* [4] | |
* [3] | |
* [2] | |
* [1] | |
* @method | |
* pop: remove most recent element of stack | |
* push: add new element to stack | |
* | |
* own added methods. | |
* peek: return last element of stack. | |
*/ | |
class Stack { | |
constructor() { | |
this._size = 0; | |
this._storage = {}; | |
} | |
} | |
/** | |
* add element to stack. | |
* 1. increment the stack size count. | |
* 2. to retain the order in which it was added, we use size as key. | |
* @param value | |
* @return updated stack | |
*/ | |
Stack.prototype.push = function(value) { | |
const size = this._size + 1; | |
this._size += 1; | |
this._storage[size] = value; | |
return this.getStack(); | |
} | |
/** | |
* 1. get reference of element. | |
* 2. decrees the size of stack | |
* 3. remove element | |
* 4. return reference of element from first step; | |
* @return removed element | |
*/ | |
Stack.prototype.pop = function() { | |
if (this._size) { | |
const value = this._storage[this._size]; | |
delete this._storage[this._size]; | |
this._size -= 1; | |
return value; | |
} | |
return undefined; | |
} | |
/** | |
* @return last element of stack. | |
*/ | |
Stack.prototype.peek = function() { | |
return this._storage[this._size - 1] | |
} | |
/** | |
* get stack | |
*/ | |
Stack.prototype.getStack = function () { | |
return this._storage; | |
} | |
/** | |
* get count | |
*/ | |
Stack.prototype.size = function () { | |
return this._size; | |
} | |
let stack = new Stack(); | |
console.log(stack.getStack()); | |
console.log(stack.push(1)); | |
console.log(stack.push(2)); | |
console.log(stack.pop()); | |
console.log(stack.push(3)); | |
console.log(stack.push([1, 2, 3, 4])); | |
console.log(stack.pop()) | |
console.log(stack.getStack()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment