Skip to content

Instantly share code, notes, and snippets.

@ragnar-johannsson
Last active August 29, 2015 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ragnar-johannsson/10509331 to your computer and use it in GitHub Desktop.
Save ragnar-johannsson/10509331 to your computer and use it in GitHub Desktop.
Local Storage Wrapper
var localStorageWrapper = {
contains: function (key) {
return this.keys().indexOf(key) !== -1;
},
getItem: function (key) {
return localStorage.getItem(key);
},
keys: function () {
var meta = JSON.parse(localStorage.getItem(this.metadataKey)) || { bytes: 0, chain: [] };
return meta.chain.map(function (v) { return v.key; });
},
metadataKey: '__meta',
removeItem: function (key) {
var meta = JSON.parse(localStorage.getItem(this.metadataKey)) || { bytes: 0, chain: [] };
for (var i = 0; i < meta.chain.length; i++) {
if (meta.chain[i].key === key) {
meta.bytes -= meta.chain[i].size;
meta.chain.splice(i, 1);
break;
}
}
localStorage.removeItem(key);
localStorage.setItem(this.metadataKey, JSON.stringify(meta));
},
setItem: function (key, val) {
while (true) {
var meta = JSON.parse(localStorage.getItem(this.metadataKey)) || { bytes: 0, chain: [] };
var valSize = encodeURI(val).split(/%..|./).length - 1;
if (this.keys().indexOf(key) !== -1) {
this.removeItem(key);
continue;
}
meta.bytes += valSize;
meta.chain.push({
key: key,
size: valSize
});
try {
localStorage.setItem(key, val);
localStorage.setItem(this.metadataKey, JSON.stringify(meta));
return;
} catch (e) {
if (meta.chain.length === 1) return;
this.removeItem(meta.chain[0].key);
}
}
},
usage: function () {
var meta = JSON.parse(localStorage.getItem(this.metadataKey)) || { bytes: 0, chain: [] };
return meta.bytes;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment