DEV Community

Discussion on: Creating 3 Stacks With 1 Array in JavaScript

Collapse
 
konrud profile image
Konstantin Rouda

Doesn't this code override the last element in the stack instead of adding it, as this.indexOfTop returns the index of the last element?

  this.values[this.indexOfTop(stackNumber)] = value;
Collapse
 
dallas profile image
Dallas Reedy • Edited

I’m thinking the same thing… if indexOfTop points at the top-most element, then setting that same index to the new value just keeps overwriting that top-most element, no?


Edit: I actually tried it the way I thought it should be (adding 1 to the value of indexOfTop) and it definitely does not do the right thing (the first element of every stack is empty, so everything is off by 1). And when I removed that code, it worked perfectly.

So, now my only question is: How is it working!? How can indexOfTop be used to both show the top-most element and to insert a new element?

Collapse
 
dallas profile image
Dallas Reedy • Edited

Oh. I see it now 🤦🏻‍♂️!

It works because of the line immediately preceding that line:

this.sizes[stackNumber]++;

That seems tricky – difficult to come back to later on and immediately understand how those lines work in concert. Perhaps it would be more straight-forward to swap those two lines and add 1 to the indexOfTop instead:

// insert our new value to the top of the stack
this.values[this.indexOfTop(stackNumber) + 1] = value;
// increment our stack size by 1
this.sizes[stackNumber]++;
Thread Thread
 
emmabostian profile image
Emma Bostian ✨

It is a bit convoluted eh?

Thread Thread
 
dallas profile image
Dallas Reedy

Yeah, maybe a little. Not too bad. Once I actually ran the code, I began to understand the cleverness at work.