Data Structures - Create a Priority Queue Class

I am trying to understand why “this” is used in the function statements only for “Create a Priority Queue Class” and not for “Create a Queue Class” or “Create a Stack Class”.

For example, returning size of Queue:

Queue Class: return collection.length;
Priority Queue Class: return this.collection.length;

Or dequeue
Queue Class: return collection.shift()
Priority Queue Class: return this.collection.shift()[0];

I tried my best to find an answer through research, but i just can’t really understand why there is a difference here. Thanks.

Your code so far

function PriorityQueue () {
  this.collection = [];
  this.printCollection = function() {
    console.log(this.collection);
  };
  // Only change code below this line
  this.enqueue = function(item) {
    let index = this.collection.findIndex(elem => elem[1] > item[1]);
    if (index !== -1) {
      this.collection.splice(index, 0, item);
    } else {
      this.collection.push(item);
    }
  }

  this.dequeue = function() {
    return this.collection.shift()[0];
  }

  this.size = function() {
    return this.collection.length;
  }

  this.isEmpty = function() {
    return this.size() === 0;
  }

  this.front = function() {
    return this.collection[0][0];
  }
  // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Data Structures - Create a Priority Queue Class

Link to the challenge:

I don’t use object prototype methods - we’ve had real classes for a while now in JS.

As I understand it…

Declaring it as:

const collection = [];

would make it a local variable to the function - you could not access it directly outside the the function - effectively private to that “class”.

I assume that:

this.collection = [];

would make it accessible as a property on the object - an instance could access that.

Really, in a perfect world, we should rewrite those lessons to at least get them up to ES6. They’re still using “var” in some cases - never a good sign. My advice might be, once you finish one, rewrite it as a class and mess around with it a bit, really understand it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.