Skip to content

Instantly share code, notes, and snippets.

@tlrobinson
Created November 2, 2011 18:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlrobinson/1334406 to your computer and use it in GitHub Desktop.
Save tlrobinson/1334406 to your computer and use it in GitHub Desktop.
Example localStorage decorators
// Storage decorator base class
function StorageDecorator(storage) {
this._storage = storage;
}
StorageDecorator.prototype.getItem = function(key) {
return this._storage.getItem(key);
}
StorageDecorator.prototype.setItem = function(key, value) {
return this._storage.setItem(key, value);
}
StorageDecorator.prototype.removeItem = function(key) {
return this._storage.removeItem(key);
}
StorageDecorator.prototype.keys = function(callback) {
return (typeof this._storage.keys === "function") ?
this._storage.keys() :
Object.keys(this._storage);
}
// Prefix key decorator
function PrefixStorage(storage, prefix) {
StorageDecorator.call(this, storage);
this._prefix = prefix || "";
}
PrefixStorage.prototype = Object.create(StorageDecorator.prototype);
PrefixStorage.prototype.getItem = function(key) {
return this._storage.getItem(this._prefix + key);
}
PrefixStorage.prototype.setItem = function(key, value) {
return this._storage.setItem(this._prefix + key, value);
}
PrefixStorage.prototype.removeItem = function(key) {
return this._storage.removeItem(this._prefix + key);
}
PrefixStorage.prototype.keys = function(callback) {
var self = this;
return self._storage.keys().filter(function(key) {
return key.indexOf(self._prefix) === 0;
}).map(function(key) {
return key.slice(self._prefix.length);
});
}
// Auto garbage collecting decorator
function GCStorage(storage, collectFilter) {
StorageDecorator.call(this, storage);
this.collectFilter = collectFilter;
}
GCStorage.prototype = Object.create(StorageDecorator.prototype);
GCStorage.prototype.setItem = function(key, value, callback) {
var self = this;
try {
self._storage.setItem(key, value);
} catch (e) {
self.gc(function(collected) {
if (collected > 0) {
self.setItem(key, value, callback);
} else {
console.warn("localStorage is full");
callback && callback(false);
}
});
return;
}
callback && callback(true);
}
GCStorage.prototype.gc = function(callback) {
console.warn("garbage collecting storage");
var self = this;
var keys = self.keys();
var collected = 0;
function next() {
if (keys.length > 0) {
var key = keys.pop();
self.collectFilter(key, function(canCollect) {
if (canCollect) {
collected++;
self.removeItem(key);
}
next();
});
} else {
callback && callback(collected);
}
}
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment