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?
You can create a class named
Queueor whatever you want. There you can implement your functionalities.Explanation
Queueconstructorfunction initialize athis.valuewith an empty array.enqueuemethod which will push the provided value at the beginning of thevalueand finally returns the instance of the class for chaining.dequeuemethod which will peek a value from the front/beginning of thevalueand also return thethisinstance.getmethod for fetching the queue's updated values.