Question about stack data structure

I bought a data structures and algorithms in javascript book recently and reached the section covering stacks. Before reading the book’s implementation I tried to implement a few of the methods:

function Stack() {
  let items = [];
  this.push = function(s) {
    items.unshift(s);
  };
  this.pop = function() {
   return items.shift();
  };
  this.peek = function() {
    return items[0];
  };
  this.isEmpty = function() {
    return items.length === 0;
  }
}

Now when I looked at the book it used the same logic, but it used the opposite end of the array instead (push, pop methods). Does it matter? Doesn’t my implementation still follow the last in first out principle?

Well sort of… but why do you need to use twisted logic?
unshift inserts new item to the front.
shift discards first item.

It matters if your underlying data structure is bad at unshift and shift.
(And perhaps, it confuses users who want to observe the data structure)

I believe it matters for the following reason…

shift and unshift have the unfortunate side effect of displacing every single item in the Array; whereas, a stack’s push and pop are usually expected to affect only the last item of the Array. From a performance perspective, your implementation gets slower and slower as the Array grows. The book’s version will have consistent performance regardless of the Array’s size.

Having said that, from experience, the fact that you are trying to build your own version ahead of reading the book’s implementation is an excellent way of learning and understanding this stuff. So, keep it up!

1 Like

@gunhoo93 That’s true! @BillSourour Wow I completely forgot about the index changes with shift and unshift, it makes sense now. And thanks!

1 Like

In fact, what @BillSourour is true. I thought the performance of unshift and shift only mattered depending on array implementation of JS engine but it seems like it is slow in general.

Thanks a lot for the info! I never really took the time to think about the underlying code of these array methods. I honestly had no idea that node has its own implementation of the Array methods.