Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Created January 22, 2018 15:41
Show Gist options
  • Save JakeTheCorn/114ebfe0aacc40177cb546f4ab846293 to your computer and use it in GitHub Desktop.
Save JakeTheCorn/114ebfe0aacc40177cb546f4ab846293 to your computer and use it in GitHub Desktop.
// Stack operations will always have a time complexity of O(1) regardless the size of the stack
var Stack = function() {
this.count = 0;
this.storage = {};
}
Stack.prototype = (function() {
return {
size: size,
push: push,
pop: pop,
peek: peek,
empty: empty,
swap: swap
}
function size() {
return this.count;
}
function push(value) {
this.storage[this.count] = value;
this.count++;
}
function pop() {
if (this.count === 0) {
return undefined;
}
this.count--;
var result = this.storage[this.count];
delete this.storage[this.count];
return result;
}
function peek() {
return this.storage[this.count - 1];
}
function empty() {
return this.count === 0;
}
function swap() {
var last = this.storage[this.count - 1];
var oneBeforeLast = this.storage[this.count - 2];
this.storage[this.count - 2] = last;
this.storage[this.count - 1] = oneBeforeLast;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment