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;
};
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;
}
};