How to use a single array to implement three stacks in JavaScript

How to use a single array to implement three stacks in JavaScript:

TripleStackTry 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
37
38
39
40
function TripleStack() {
this._array = [];
this._lengths = [0, 0, 0];
}
TripleStack.prototype._getLength = function(stack) {
return this._lengths[stack-1];
};
TripleStack.prototype.push = function(stack, val){
const idx = this._getLength(stack) * 3 + stack - 1;
this._array[idx] = val;
this._lengths[stack - 1]++; // we reference stacks w/ 1, 2, 3 but internally stack lengths start their indices at 0
};
TripleStack.prototype.pop = function(stack) {
let len = this._getLength(stack);
let val;
if (len) {
const idx = (len - 1) * 3 + stack - 1;
val = this._array[idx];
delete this._array[idx];
this._lengths[stack - 1]--;
}
return val;
};
TripleStack.prototype.peek = function(stack) {
let len = this._getLength(stack);
let val;
if (len) {
const idx = (len - 1) * 3 + stack - 1;
val = this._array[idx];
}
return val;
};
TripleStack.prototype.isEmpty = function(stack) {
return this._getLength(stack) === 0;
};

Tests can be found at REPL.it.