jsでスタックをTypedArrayで組んでみる

ちょっと煮詰まってるので現実逃避。

javascriptで配列の数を制限したい (スタック・オーバーフロー)

こちらをTypedArrayで書いてみました。

実行例


stack=new Stack(3)
stack.pop()

Error: stack empty

stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)

Error: stack overflow

stack.pop()

 3

stack.pop()

 2

stack.pop()

 1

stack.pop()

Error: stack empty


function Stack(sz){
this._stack=new Float64Array(sz);
this._sp=0;
this.push=function(x){
if(this._sp<sz){
this._stack[this._sp++]=x
} else {
throw "stack overflow";
}
};
this.pop=function(){
if(this._sp>0){
return this._stack[--this._sp];
} else {
throw "stack empty";
}
}
}