JavaScript の循環バッファ 質問する

JavaScript の循環バッファ 質問する

すでに JavaScript で循環バッファを実装した人はいますか? ポインタなしでそれをどうやって実現するのでしょうか?

ベストアンサー1

奇妙な偶然ですが、ちょうど今日、1 つ書きました。あなたの要件が正確に何であるかはわかりませんが、これは役に立つかもしれません。

無制限の長さの配列のようなインターフェースを提示しますが、古い項目は「忘れられます」。

// Circular buffer storage. Externally-apparent 'length' increases indefinitely
// while any items with indexes below length-n will be forgotten (undefined
// will be returned if you try to get them, trying to set is an exception).
// n represents the initial length of the array, not a maximum
function CircularBuffer(n) {
    this._array= new Array(n);
    this.length= 0;
}
CircularBuffer.prototype.toString= function() {
    return '[object CircularBuffer('+this._array.length+') length '+this.length+']';
};
CircularBuffer.prototype.get= function(i) {
    if (i<0 || i<this.length-this._array.length)
        return undefined;
    return this._array[i%this._array.length];
};
CircularBuffer.prototype.set= function(i, v) {
    if (i<0 || i<this.length-this._array.length)
        throw CircularBuffer.IndexError;
    while (i>this.length) {
        this._array[this.length%this._array.length]= undefined;
        this.length++;
    }
    this._array[i%this._array.length]= v;
    if (i==this.length)
        this.length++;
};
CircularBuffer.IndexError= {};

おすすめ記事