How to implement a Queue in JavaScript

Here is a reference implementation for a Queue:

QueueTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function Queue() {
this.size = 0;
this.first = this.last = null;
}
function Node(data) {
this.data = data;
this.next = null;
}
Queue.prototype.add = function(data) {
const node = new Node(data);
if (this.last) this.last.next = node;
this.last = node;
if (!this.first) this.first = this.last;
this.size++;
};
Queue.prototype.dequeue = function() {
if (!this.first) return;
const data = this.first.data;
this.first = this.first.next;
if (!this.first) this.last = null;
this.size = Math.max(0, this.size - 1);
return data;
};
Queue.prototype.peek = function() {
if (!this.first) return;
return this.first.data;
};
Queue.prototype.isEmpty = function() {
return this.size === 0 && !this.first;
};

Tests can be found at REPL.it