A stack is a data structure that is based on the concept of “last-in-first-out” or “LIFO.” You can think of it like a stack of books where the top book has to be taken off the stack before you can retrieve the bottom book. JavaScript doesn’t have a native stack data structure, so we’re going to create one today.
Our array will contain three different stacks of a fixed size. The top of the stack will be on the right side and the bottom of the stack will be on the left side. You can picture it similar to this diagram. If this stack was full, the bottom element would live at stack[0]
and the top element would live at stack[stack.length-1]
.
Our stacks will have a fixed size which will be equal to the argument passed in at instantiation.
The following properties will be initialized within the constructor:
Our MultiStack class will contain the following methods:
The first thing we’ll do is create our constructor. It will take in one argument, the stack size. Thus, the total length of our values array will be 3 * the stack size (since we’re initializing numberOfStacks to three).
We will initialize the sizes array to contain three indices with the value zero. For our purposes we will assume that the values being pushed onto the stacks are positive integers. You can change this logic to fit your needs.
class MultiStack {
constructor(stackSize) {
this._stackCapacity = stackSize;
this.values = [];
this.sizes = [0, 0, 0];
this.numberOfStacks = 3;
}
}
This method returns the total capacity of each of the stacks (this is just a way for me to check that everything is working as expected, we won’t really be using this.)
You can read more about JavaScript getters on MDN.
get stackCapacity() {
return this._stackCapacity;
}
This method returns a boolean which indicates whether the respective stack is full. It will check how many elements are currently on the respective stack and compare it against the stack capacity.
isFull(stackNumber) {
return this.sizes[stackNumber] === this._stackCapacity;
}
This method returns a boolean which indicates whether the respective stack has values.
isEmpty(stackNumber) {
return this.sizes[stackNumber] === 0;
}
This is a helper method which returns the index, in the values array, of the top element in the respective stack.
This explanation could get a little tricky, so stick with it! I’ve included diagrams to better visualize the process.
First we need to grab the offset of the stack within the values array. To do this, we’ll multiply the stack number we want by the capacity of each stack.
For example, let’s find the index of the top item in stack 2 given that the _stackCapacity
for each stack is 5. The stacks contain the following elements:
Here is a visual representation of what the values array looks like:
Step 1: Calculate the offset; find the index of the bottom item in stack two
Assuming our stacks start at zero (i.e. stack 0, stack 1, stack 2), we can find where the bottom of stack two starts in the values array by multiplying the stack we’re looking for, two, by the stack capacity, which is the value passed in at instantiation. If our stack capacity is five, we know that the bottom element of stack two starts at index 10 in the values array.
index of bottom element in stack 2 = stack we’re looking for * capacity of each stack.
index of bottom element in stack 2 = 2 * 5 (found from <em>_stackCapacity</em>
)
index of bottom element in stack 2 = 10.
Step 2: Calculate the total number of values currently in stack two
We already know how many values are in stack 2; they’re being kept in the sizes
array. So by grabbing the value of sizes[2]
we know how many elements are in stack 2: 4
Step 3: Add the offset with the total number of values in the stack, minus one
We have to subtract one from the number of items in the stack, since our array starts at index zero.
When we add it all up we get:
index of top element in stack 2 = offset + number of values in stack two— 1
index of top element in stack 2 = 10 + 4 — 1
index of top element in stack 2 = 13
The code for this is as follows:
indexOfTop(stackNumber) {
const offset = stackNumber * this._stackCapacity; // Find the starting point in the array
const size = this.sizes[stackNumber]; // How many elements are in that stack currently?
return offset + size - 1;
}
The push method pushes a value onto the top of the respective stack. It takes in two arguments:
The first thing we have to do is check whether the stack is full. If it is full, let’s console.log
the message Stack number ${stackNumber} is full
.
If the stack isn’t full, increase the number of items in the stack, which is found in the sizes
array.
Then add the new value to the top of the stack. We’ll use the indexOfTop
method we just explained above to grab the top of the stack and add a value on top of it.
If it’s successfully added, let’s console.log
a friendly message.
push(stackNumber, value) {
if (this.isFull(stackNumber)) {
return console.log(`Stack number ${stackNumber} is full`);
}
// Add one to the respective stack count
this.sizes[stackNumber]++;
// Add the value to the list
this.values[this.indexOfTop(stackNumber)] = value;
return console.log(`Item ${value} has been successfully added to stack ${stackNumber}`);
}
This method pops the top item off of the respective stack number. It takes in one argument:
isEmpty
method. If it is, we’ll return a console.log
a message.indexOfTop
method and save it to a variable called topIndex
.this.values[topIndex]
. We’ll return this element, which is why we need to save it to a variable.this.sizes[stackNumber]--
.pop(stackNumber) {
if (this.isEmpty(stackNumber)) {
return console.log(`Stack number ${stackNumber} is empty`);
}
const topIndex = this.indexOfTop(stackNumber);
const value = this.values[topIndex];
this.values[topIndex] = 0; // Clear out element
this.sizes[stackNumber]--; // Reduce num elements in the stack
return value;
}
This method returns the top item off of the respective stack number. It doesn’t alter the stack, it simply lets you view the element on the top. It takes in one argument:
isEmpty
method to do so. If it is empty, let’s console.log
a friendly message.indexOfTop
method to do so.this.values[topIndex]
.peek(stackNumber) {
if (this.isEmpty(stackNumber)) {
console.log(`Stack number ${stackNumber} is empty`);
}
const topIndex = this.indexOfTop(stackNumber);
return this.values[topIndex];
}
The final class looks like this:
class MultiStack {
constructor(stackSize) {
this._stackCapacity = stackSize;
this.values = []; // values in the stack which is max size of stackSize * 3
this.sizes = [0,0,0]; // length of 3 and each index contains the number of items in the respective stack
this.numberOfStacks = 3;
}
get stackCapacity() {
return this._stackCapacity;
}
push(stackNumber, value) {
if (this.isFull(stackNumber)) {
return console.log(`Stack number ${stackNumber} is full`);
}
// Add one to the respective stack count
this.sizes[stackNumber]++;
// Add the value to the list
this.values[this.indexOfTop(stackNumber)] = value;
return console.log(`Item ${value} has been successfully added to stack ${stackNumber}`);
}
pop(stackNumber) {
if (this.isEmpty(stackNumber)) {
return console.log(`Stack number ${stackNumber} is empty`);
}
const topIndex = this.indexOfTop(stackNumber);
const value = this.values[topIndex];
this.values[topIndex] = 0; // Clear out element
this.sizes[stackNumber]--; // Reduce num elements in the stack
return value;
}
peek(stackNumber) {
if (this.isEmpty(stackNumber)) {
console.log(`Stack number ${stackNumber} is empty`);
}
const topIndex = this.indexOfTop(stackNumber);
return this.values[topIndex];
}
isEmpty(stackNumber) {
return this.sizes[stackNumber] === 0;
}
isFull(stackNumber) {
return this.sizes[stackNumber] === this._stackCapacity;
}
indexOfTop(stackNumber) {
const offset = stackNumber * this._stackCapacity; // Find the starting point in the array
const size = this.sizes[stackNumber]; // How many elements are in that stack currently?
return offset + size - 1;
}
}
You’ve now created an array that represents three fixed-size stacks! You can view the CodePen for this class here.
#javascript