In a current javascript project, I'm working with the browsers localStorage, and it will pretty consistently be full. To overcome this, I wrote a wrapper to surround the localStorage object that would keep track of when an object was added.
The hard(er) part, was coming up with the algorithm to make room for any new data. I was wondering if anyone could critique my method, and let me know if a better method exists.
DataStore.prototype.makeRoom = function() {
var tmpData = {};
for (var key in localStorage) {
var expTime = JSON.parse(localStorage.getItem(key)).expirationTime;
if (Object.size(tmpData) < 3) {
tmpData[key] = expTime;
continue;
}
for (var tmpKey in tmpData) {
var tmpExp = JSON.parse(localStorage.getItem(tmpKey)).expirationTime;
if (tmpExp > expTime) {
delete tmpData[tmpKey];
tmpData[key] = expTime;
break;
}
}
}
for (var deleteKey in tmpData) {
this.destroyItem(deleteKey);
}
return true;
};
And for reference, DataStore.destroyItem(), and DataStore.store() where the data is written:
DataStore.prototype.store = function(dataKey, data, minutesUntilExpiration, overWrite) {
if (!overWrite && this.hasItem(dataKey))
return false;
var dataToSave = {
data: data,
expirationTime: (new Date().getTime() + (minutesUntilExpiration * 60 * 1000))
};
try {
localStorage.setItem(dataKey, JSON.stringify(dataToSave));
} catch (e) {
this.makeRoom();
this.store(dataKey,data,minutesUntilExpiration,overWrite);
}
return true;
};
DataStore.prototype.destroyItem = function(dataKey) {
if (this.hasItem(dataKey)) {
localStorage.removeItem(dataKey);
return true;
}
return false;
};
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};