Skip to content

Instantly share code, notes, and snippets.

@oddlyfunctional
Created June 13, 2016 16:13
Show Gist options
  • Save oddlyfunctional/34dc11de90c9ff39e9f6abd4805d4744 to your computer and use it in GitHub Desktop.
Save oddlyfunctional/34dc11de90c9ff39e9f6abd4805d4744 to your computer and use it in GitHub Desktop.
var Stack = function(){
this.storage = "";
this.frameSize = 20;
this.emptySpaceChar = '$';
};
Stack.prototype.paddingRight = function(val) {
for(var i = val.length; i <= this.frameSize; i++) {
val += this.emptySpaceChar;
}
return val;
}
Stack.prototype.validateValue = function(val) {
if (typeof val != "string") {
throw new Error("Item can only be a string");
}
if (val.indexOf('$') != -1) {
throw new Error("Item cannot contain the empty space character: " + this.emptySpaceChar);
}
if (val.length > this.frameSize) {
throw new Error("Item cannot be longer than " + this.frameSize + " characters");
}
}
Stack.prototype.push = function(val){
this.validateValue(val);
val = this.paddingRight(val);
this.storage += val;
};
Stack.prototype.pop = function(){
var newEnd = this.storage.length - this.frameSize - 1;
var top = this.storage.substr(newEnd, this.storage.length);
this.storage = this.storage.substr(0, newEnd);
top = top.substr(0, top.indexOf(this.emptySpaceChar));
return top;
};
Stack.prototype.size = function(){
return this.storage.length / this.frameSize;
};
var myWeeklyMenu = new Stack();
myWeeklyMenu.push("RedBeans");
myWeeklyMenu.push("Pasta");
myWeeklyMenu.push("Rice and beans");
myWeeklyMenu.push("Salad");
while(myWeeklyMenu.size()) {
console.log(myWeeklyMenu.pop());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment