Consider the following stack class in Javascript with few small helper functions.
Example
class Stack { constructor(maxSize) { // Set default max size if not provided if (isNaN(maxSize)) { maxSize = 10; } this.maxSize = maxSize; // Init an array that'll contain the stack values. this.container = []; } // A method just to see the contents while we develop this class display() { console.log(this.container); } // Checking if the array is empty isEmpty() { return this.container.length === 0; } // Check if array is full isFull() { return this.container.length >= maxSize; } }
Here the isFull function just checks if the length of container is equal to or more than maxSize and returns accordingly. The isEmpty function checks if size of the container is 0.
In this section, we are going to add PUSH operation in this class. Pushing elements to a Stack means adding them to the top of the array. We are taking the end of the container array to be the top of the array as we'll perform all operations with respect to it. So we can implement the push function as follows −
Example
push(element) { // Check if stack is full if (this.isFull()) { console.log("Stack Overflow!"); return; } this.container.push(element); }
You can check if this function is working fine using −
Example
let s = new Stack(2); s.display(); s.push(10); s.push(20); s.push(30); s.display();
Output
This will give the output −
[] Stack Overflow! [ 10, 20 ]