JavaScript中的循环缓冲区 [英] Circular buffer in JavaScript

查看:144
本文介绍了JavaScript中的循环缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人已经在JavaScript中实现了循环缓冲区?

解决方案

奇怪的共同发生,我今天刚写了一个!我不知道你的要求是什么,但这可能是有用的。



它提供了一个无限长度的数组的接口,但是忘记旧项:

  //循环缓冲存储。外部明显的'长度'无限期增加
//而索引低于length-n的任何项目将被遗忘(未定义的
//将返回,如果您尝试获取它们,尝试设置是一个异常)。
// n表示数组的初始长度,而不是最大
函数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 return undefined;
return this._array [i%this._array.length];
};
CircularBuffer.prototype.set = function(i,v){
if(i <0 || i 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 = {};


Has anyone already implemented a circular buffer in JavaScript? How would you do that without having pointers?

解决方案

Strange co-incidence, I just wrote one earlier today! I don't know what exactly your requirements are but this might be of use.

It presents an interface like an Array of unlimited length, but ‘forgets’ old items:

// 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= {};

这篇关于JavaScript中的循环缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆