Creating a derived array type in JavaScript

155 Views Asked by At

I'd like to make my own JavaScript queue type based on JS Array. I'd like instances of my queue to be fully functional instances of JS arrays. I'd like for them to have some extra methods, starting with an enq (enqueue) and deq (dequeue) methods. My first attempt failed, for reasons I don't understand.

function makeQueue_attempt_1() {
  let prototype = Object.create(Array.prototype);
  prototype.enq = Array.prototype.shift;
  prototype.deq = Array.prototype.pop;
  return Object.create(prototype);
}

Question 1: why doesn't my implementation work? Is it even a good idea or should what I want to do be done by some other method?

Question 2: what would be a better approach?

1

There are 1 best solutions below

2
Sajeeb Ahamed On

You can create a class named Queue or whatever you want. There you can implement your functionalities.

class Queue {
  constructor() {
      this.value = [];
  }

  enqueue(val) {
    this.value.push(val);
    return this;
  }
  
  dequeue() {
    this.value.shift();
    return this;
  }
  
  get() {
    return this.value;
  }
}

const queue = new Queue();
queue.enqueue(20)
  .enqueue(10)
  .enqueue(22);

console.log('after enqueued:', queue.get());

queue.dequeue();
console.log('after dequeued:', queue.get());

Explanation

  1. Create a class named Queue
  2. Inside the constructor function initialize a this.value with an empty array.
  3. Create an enqueue method which will push the provided value at the beginning of the value and finally returns the instance of the class for chaining.
  4. Create a dequeue method which will peek a value from the front/beginning of the value and also return the this instance.
  5. Create a get method for fetching the queue's updated values.