Skip to content

Instantly share code, notes, and snippets.

@mitrakmt
Created September 19, 2016 03:27
Show Gist options
  • Save mitrakmt/ceb1aefda6aa97facb104a49a2b9dbc3 to your computer and use it in GitHub Desktop.
Save mitrakmt/ceb1aefda6aa97facb104a49a2b9dbc3 to your computer and use it in GitHub Desktop.
Stack Data Structure in JavaScript
// This Stack is written using the pseudoclassical pattern
// Creates a stack
var Stack = function() {
this.count = 0;
this.storage = {};
}
// Adds a value onto the end of the stack
Stack.prototype.push = function(value) {
this.storage[this.count] = value;
this.count++;
}
// Removes and returns the value at the end of the stack
Stack.prototype.pop = function() {
// Check to see if the stack is empty
if (this.count === 0) {
return undefined;
}
this.count--;
var result = this.storage[this.count];
delete this.storage[this.count];
return result;
}
// Returns the length of the stack
Stack.prototype.size = function() {
return this.count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment