Created
August 25, 2016 09:54
-
-
Save vwochnik/0f15d1a04ecc7c5e92e4f0fce61870d3 to your computer and use it in GitHub Desktop.
Local Storage getter/setter with expiration
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
/** | |
* Retrieves or stores a value inside local storage. | |
* If only the first parameter is specified, the value is retrieved from local storage. | |
* If a value to store is specified, maxAge must also be specified after which the value is | |
* considered invalid and removed during successive retrievals. | |
* @param name key name to set or retrieve | |
* @param value value to store | |
* @param maxAge number of hours until expiration | |
*/ | |
function storage(name, value, maxAge) { | |
if (value !== void 0) { | |
var expires = new Date(Date.now() + maxAge * 3600000); | |
window.localStorage.removeItem(name); | |
window.localStorage.setItem(name, JSON.stringify({ | |
value: JSON.stringify(value), | |
expires: expires.toUTCString() | |
})); | |
return value; | |
} | |
try { | |
var obj = JSON.parse(window.localStorage.getItem(name)); | |
if (new Date(obj.expires) < new Date()) { | |
window.localStorage.removeItem(name); | |
} | |
return JSON.parse(obj.value); | |
} catch (e) { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment