|
8 | 8 | // Functions: push, pop, peek, view, length
|
9 | 9 |
|
10 | 10 | // Creates a stack constructor
|
11 |
| -const Stack = (function () { |
12 |
| - class Stack { |
13 |
| - constructor() { |
14 |
| - // The top of the Stack |
15 |
| - this.top = 0 |
16 |
| - // The array representation of the stack |
17 |
| - this.stack = [] |
18 |
| - } |
19 |
| - |
20 |
| - // Adds a value onto the end of the stack |
21 |
| - push(value) { |
22 |
| - this.stack[this.top] = value |
23 |
| - this.top++ |
24 |
| - } |
| 11 | +class Stack { |
| 12 | + constructor() { |
| 13 | + // The top of the Stack |
| 14 | + this.top = 0 |
| 15 | + // The array representation of the stack |
| 16 | + this.stack = [] |
| 17 | + } |
25 | 18 |
|
26 |
| - // Removes and returns the value at the end of the stack |
27 |
| - pop() { |
28 |
| - if (this.top === 0) { |
29 |
| - return 'Stack is Empty' |
30 |
| - } |
| 19 | + // Adds a value onto the end of the stack |
| 20 | + push(value) { |
| 21 | + this.stack[this.top] = value |
| 22 | + this.top++ |
| 23 | + } |
31 | 24 |
|
32 |
| - this.top-- |
33 |
| - const result = this.stack[this.top] |
34 |
| - this.stack = this.stack.splice(0, this.top) |
35 |
| - return result |
| 25 | + // Removes and returns the value at the end of the stack |
| 26 | + pop() { |
| 27 | + if (this.top === 0) { |
| 28 | + return 'Stack is Empty' |
36 | 29 | }
|
37 | 30 |
|
38 |
| - // Returns the size of the stack |
39 |
| - size() { |
40 |
| - return this.top |
41 |
| - } |
| 31 | + this.top-- |
| 32 | + const result = this.stack[this.top] |
| 33 | + this.stack = this.stack.splice(0, this.top) |
| 34 | + return result |
| 35 | + } |
42 | 36 |
|
43 |
| - // Returns the value at the end of the stack |
44 |
| - peek() { |
45 |
| - return this.stack[this.top - 1] |
46 |
| - } |
| 37 | + // Returns the size of the stack |
| 38 | + size() { |
| 39 | + return this.top |
| 40 | + } |
47 | 41 |
|
48 |
| - // To see all the elements in the stack |
49 |
| - view(output = (value) => console.log(value)) { |
50 |
| - for (let i = 0; i < this.top; i++) { |
51 |
| - output(this.stack[i]) |
52 |
| - } |
53 |
| - } |
| 42 | + // Returns the value at the end of the stack |
| 43 | + peek() { |
| 44 | + return this.stack[this.top - 1] |
54 | 45 | }
|
55 | 46 |
|
56 |
| - return Stack |
57 |
| -})() |
| 47 | + // To see all the elements in the stack |
| 48 | + view(output = (value) => console.log(value)) { |
| 49 | + for (let i = 0; i < this.top; i++) { |
| 50 | + output(this.stack[i]) |
| 51 | + } |
| 52 | + } |
| 53 | +} |
58 | 54 |
|
59 | 55 | export { Stack }
|
0 commit comments