|
| 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