Skip to content

Instantly share code, notes, and snippets.

@akhoury
Last active August 29, 2015 14:08
Show Gist options
  • Save akhoury/13ecbbe06c4385899512 to your computer and use it in GitHub Desktop.
Save akhoury/13ecbbe06c4385899512 to your computer and use it in GitHub Desktop.
var isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
var getStorage = function(key) {
var data = localStorage.getItem(key),
ttl = localStorage.getItem(key + '-ttl'),
expired = ttl == null ? false : ttl < (new Date()).getTime();
if (!expired) {
return data;
}
};
var setStorage = function(key, data, options) {
options = options || {};
var ttl = options.ttl ? isNumber(options.ttl) && ttl > 0 ? options.ttl : 24 * 60 * 60 * 1000 /* ttl is truthy ? 24 hours default */ : false;
localStorage.setItem(key, data);
if (ttl) {
localStorage.setItem(key + '-ttl', new Date().getTime() + ttl);
}
return getStorage(key);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment