How to implement a set of stacks in JavaScript

Here is one way to implement a data structure that allows for push and pop operations, pushing a new stack when a previous stack exceeds its capacity. Pop should remove a stack if the top stack is empty.

SetOfStacksTry 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function SetOfStacks(stackSize) {
if (arguments.length < 1) throw new Error('You must provide a stack size limit as your first argument');
this.stacks = [[]];
this.max = stackSize;
}
SetOfStacks.prototype.push = function(value) {
if (this.stacks[this.stacks.length-1].length >= this.max) {
this.stacks.push([])
}
this.stacks[this.stacks.length-1].push(value);
};
SetOfStacks.prototype.pop = function() {
const value = this.stacks[this.stacks.length-1].pop();
if (this.stacks.length && this.stacks[this.stacks.length - 1].length === 0) {
this.stacks.pop();
}
return value;
};
// this method is more complex than the rest
// if it's okay to have semi-full stacks in the middle, users may be surprised
SetOfStacks.prototype.popAt = function(stackNum) {
if (stackNum < 1 || stackNum > this.stacks.length) {
throw new Error('Invalid stack number');
}
if (stackNum === this.stacks.length) {
return this.pop();
}
let stack = this.stacks[stackNum-1];
let value = stack.pop();
const tempStack = [];
let nextStack;
if (stackNum < this.stacks.length) {
for (let i = stackNum; i < this.stacks.length; i++) {
nextStack = this.stacks[i];
while (nextStack.length) {
tempStack.push(nextStack.pop());
}
stack.push(tempStack.pop());
while (tempStack.length) {
nextStack.push(tempStack.pop());
}
stack = nextStack;
}
if (this.stacks.length > 1 && this.stacks[this.stacks.length-1].length === 0) {
this.stacks.pop();
}
return value;
}
};

Tests can be found at REPL.it