Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Implementation of a stack and cheaty stack in JavaScript. (NOTE: I stupidly deleted my testing code... I need to rewrite it (better) and put it back in. Apologies!)
var assert = require("assert"); // node needs this module
// CHEATING STACK (using built-in functions):
function CheatingStack () {
this.contents = [];
}
CheatingStack.prototype.push = function (item) {
this.contents.push(item);
};
CheatingStack.prototype.pop = function () {
return this.contents.pop();
}
CheatingStack.prototype.isEmpty = function () {
return (this.contents.length === 0);
}
// STACK using only objects:
function Item (value, prevItem) {
this.value = value;
this.prevItem = prevItem;
}
function LinkedListStack () {
this.head = null;
}
LinkedListStack.prototype.push = function (item) {
var newItem = new Item (item, this.head);
this.head = newItem;
};
LinkedListStack.prototype.pop = function() {
if (this.isEmpty()) {
return false;
}
else {
var returnItem = this.head;
this.head = returnItem.prevItem;
return returnItem.value;
}
}
LinkedListStack.prototype.isEmpty = function() {
return (this.head === null);
}
// CLIENT CODE: testing our implementation
var myStack = new LinkedListStack();
// Yes... I deleted my testing code because it was imperfect. Yes, I need to rewrite it and put it back in. Perhaps after I finish writing about what I just learned!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment