Welcome to Mr. Spurgeon's Awesome Lesson on Stacks!
function ArrayStack() {
// Values
const array = [];
// Operations
const operations = {
isEmpty: function() {
return array.length === 0;
},
push: function(value) {
array.push(value);
return operations;
},
pop: function() {
return array.pop();
}
};
return operations;
}
function LimitedArrayStack(limit) {
// Values
const array = [];
let size = 0;
// Operations
const operations = {
isEmpty: function() {
return size === 0;
},
push: function(value) {
if (size < limit) {
array[size] = value;
size = size + 1;
}
return operations;
},
pop: function() {
let value = null;
if (size > 0) {
size = size - 1;
value = array[size];
}
return value;
}
};
return operations;
}
function NodeStack() {
// Values
let top = null;
// Operations
const operations = {
isEmpty: function() {
return top === null;
},
push: function(value) {
top = {value: value, next: top };
return operations;
},
pop: function() {
let value = null;
if (top !== null) {
value = top.value;
top = top.next;
}
return value;
}
};
return operations;
}
function useStack(stack) {
stack.push("apples").push("berries").push("cats");
while(!stack.isEmpty()) alert(stack.pop());
}
useStack(NodeStack());
useStack(ArrayStack());
useStack(LimitedArrayStack(2));