我正在构建一个基本的 MinArray,即一个数组包装器,它将已删除的 id 推送到队列中,并在增加长度之前重用回收的 id;
但是,我的 MinArray 不会回收 id,它只是不断增加。
完整的代码和测试可以在这个fiddle找到。
此代码插入一个新值并返回分配的 id:
MinArray.prototype.insert = function(val){
var id;
var recycledId = this._recycledIds.shift();
if(recycledId){
id = recycledId;
}else{
id = this._nextId++;
}
this._vals[id] = val;
this._executeCallbacks(this.oninsert, this._vals[id]);
this.length++;
return id;
};
这段代码从数组中删除一个项目:
MinArray.prototype.remove = function(id){
if(this._vals[id]){
this._executeCallbacks(this.onremove, this._vals[id]);
delete this._vals[id];
this._recycledIds.push(id);
this.length--;
return true;
}else{
return false;
}
};
或者,您知道我可以自由使用的任何好的现有实现吗?