Last active
August 29, 2015 14:08
-
-
Save akhoury/13ecbbe06c4385899512 to your computer and use it in GitHub Desktop.
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 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