Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active May 15, 2016 06:16
Show Gist options
  • Save Williammer/0664978c9448ea413979de131d13bd5e to your computer and use it in GitHub Desktop.
Save Williammer/0664978c9448ea413979de131d13bd5e to your computer and use it in GitHub Desktop.
Stack data structure in javaScript.
function Stack() {
// this._size = 0;
// this._storage = {};
this._storage = []; // array could be more performant due to array browser optimize
}
Stack.prototype.push = function (data) {
// var size = ++this._size;
var len = this._storage.length;
this._storage[len] = data;
};
Stack.prototype.peek = function () {
var len = this._storage.length;
return this._storage[len-1];
};
Stack.prototype.clear = function () {
this._storage.length = 0;
};
Stack.prototype.pop = function () {
var len = this._storage.length,
deletedData;
if (len > 0) {
deletedData = this._storage[this._storage.length--];
// delete this._storage[size];
// this._storage[size] = null; // set to null clear mem than delete.
// this._size--;
return deletedData;
}
};
var stack = [];
// first in
stack.push("a");
stack.push("b");
// last out
stack.pop(); // "b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment