DEV Community

Discussion on: Creating 3 Stacks With 1 Array in JavaScript

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.