thatandrey
thatandrey

Reputation: 287

Clear method is unclear when implementing stacks in JS

I was recently looking at this book chapter, which explained how to create stacks in JS. This is the code:

function Stack() {
   this.dataStore = [];
   this.top = 0;
   this.push = push;
   this.pop = pop;
   this.peek = peek;
   this.clear = clear;
   this.length = length;
}

function push(element) {
   this.dataStore[this.top++] = element;
}

function peek() {
   return this.dataStore[this.top-1];
}

function pop() {
   return this.dataStore[--this.top];
}

function clear() {
   this.top = 0;
}

function length() {
   return this.top;
}

I'm having trouble understanding the clear() method. Why does setting the top to 0 clear the array? I was also expecting the line this.dataStore.length = 0. It seems like setting the top to 0 only changes the pointer and the dataStore is unchanged, meaning that further operations would just overwrite the previous dataStore values. Can anyone explain what's going on? Thanks!

Upvotes: 0

Views: 57

Answers (2)

Oriol
Oriol

Reputation: 287990

It seems like setting the top to 0 only changes the pointer and the dataStore is unchanged, meaning that further operations would just overwrite the previous dataStore values.

You are absolutely right. And I agree this behavior may be undesirable.

Instead, I suggest the following:

function Stack() {
   this.dataStore = [];
}
Object.assign(Stack.prototype, {
  push: function(element) {
    this.dataStore.push(element);
  },
  peek: function() {
    return this.dataStore[this.dataStore.length-1];
  },
  pop: function() {
    return this.dataStore.pop();
  },
  clear: function() {
    this.dataStore.length = 0;
  },
  length: function() {
    return this.dataStore.length;
  }
});

Upvotes: 1

just-boris
just-boris

Reputation: 9746

Data store isn't cleared because it is not necessary. While you are using this stack object, you don't need to work with dataStore directly, only via functions of Stack object.

So you can remain dataStore unchanged, it allows you to do same work with less operation and maybe faster.

Upvotes: 1

Related Questions