Skip to content

Instantly share code, notes, and snippets.

@osapon
Last active February 1, 2016 14:11
Show Gist options
  • Save osapon/3f9fdd789e95bfeb1d95 to your computer and use it in GitHub Desktop.
Save osapon/3f9fdd789e95bfeb1d95 to your computer and use it in GitHub Desktop.
localStorage.js
(function (lstorage) {
lstorage.set = function(name,val) {
while(true) {
var key_name = '', old_dt = Date.now();
try{
localStorage.setItem(name, window.JSON.stringify({
'data':val,
'dt':Date.now()
}));
}
catch(e) {
Object.keys(localStorage).forEach( function(val) {
var obj = window.JSON.parse(localStorage.getItem(val));
if (obj.dt < old_dt) {
old_dt = obj.dt;
key_name = val;
}
});
if ( key_name != '' ) {
localStorage.removeItem(key_name);
}
}
if ( key_name == '' ) break;
}
}
lstorage.get = function(name) {
var obj = window.JSON.parse(localStorage.getItem(name));
if (obj) return obj.data;
return null;
}
lstorage.clear = function() {
localStorage.clear();
}
})(osapon.lstorage = osapon.lstorage || {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment