codersun3
codersun3

Reputation: 175

Creating a queue in Javascript

I'm writing a queue in javascript, and am not sure what is the best way to implement it:

Option 1:

Do something like...

var queue = []

...and use push/shift functions to enqueue/dequeue.

Option 2:

Create an object like so:

var myQueue = new function() {
  this.queue = [];
  this.enqueue(x) = function() { this.queue.push(x) };
  this.dequeue() = function { this.queue.shift() };
}

Option 3:

Something else that you suggest?

The only advantage that I can see to using option 2 over 1 is that if I want to create a unique method to call on myQueue (e.g. dequeueTwoElements), I'd be able to do so.

Thoughts?

Upvotes: 0

Views: 1223

Answers (1)

dm03514
dm03514

Reputation: 55962

I don't think there IS a best way to implement it. Wrapping your queue in a custom object will provide all the benefits of encapsulation, and implementation hiding.

Suppose for some reason you wanted to change myQueue to use an object instead of an array internally, it would allow you to do that, without messing up any of its clients.

Additionally, I think it will be easier for someone new to your code to explicitly understand that your queue is indeed a queue. This is because they have a function constructor definition to look at, and the enqueue and dequeue function are more explicit then passing around an array named queue and calling js array methods on it.

Upvotes: 3

Related Questions