Skip to content

Commit

Permalink
Implement constantTimeStackMin.js
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Dec 31, 2014
1 parent 4535f4b commit b593183
Showing 1 changed file with 29 additions and 9 deletions.
38 changes: 29 additions & 9 deletions constantTimeStackMin/constantTimeStackMin.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,43 @@
/**
* Stack Class
*/
var Stack = function() {
var Stack = function () {
var storage = {};
var minSoFar = [];
var top = 0;

// add an item to the top of the stack
this.push = function(value){
this.push = function (value) {
if ( minSoFar.length === 0 || value <= minSoFar[minSoFar.length - 1] ) {
minSoFar.push( value );
}
storage[top] = value;
top += 1;
};

// remove an item from the top of the stack
this.pop = function(){
this.pop = function () {
var popped;
if ( this.size() > 0) {
popped = storage[top - 1];
delete storage[top - 1];
top -= 1;

if ( popped === minSoFar[minSoFar.length - 1] ) {
minSoFar.pop();
}
return popped;
}
};

// return the number of items in the stack
this.size = function(){
}
this.size = function () {
return top;
};

this.min = function() {
this.min = function () {
return minSoFar[minSoFar.length - 1];
};

}
return this;
};

};

0 comments on commit b593183

Please sign in to comment.