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