How to implement a queue using two stacks in JavaScript

Here is how to implement a Queue using two stacks in JavaScript:

QueueStackTry 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
36
function Queue() {
this._inStack = [];
this._outStack = [];
}
Queue.prototype.enqueue = function(value) {
this._inStack.push(value);
};
Queue.prototype.dequeue = function() {
if (this._outStack.length) {
return this._outStack.pop();
}
while (this._inStack.length) {
this._outStack.push(this._inStack.pop());
}
return this._outStack.length ? this._outStack.pop() : undefined;
};
Queue.prototype.getSize = function() {
return this._inStack.length + this._outStack.length;
}
Queue.prototype.peek = function() {
if (this._outStack.length) {
return this._outStack[this._outStack.length-1];
}
while (this._inStack.length) {
this._outStack.push(this._inStack.pop());
}
return this._outStack.length ? this._outStack[this._outStack.length - 1] : undefined;
};
Queue.prototype.isEmpty = function() {
return (this._inStack.length + this._outStack.length) === 0;
};

Tests can be found at REPL.it