Last active
August 29, 2015 13:59
-
-
Save ragnar-johannsson/10509331 to your computer and use it in GitHub Desktop.
Local Storage Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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