Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@vwochnik
Created August 25, 2016 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vwochnik/0f15d1a04ecc7c5e92e4f0fce61870d3 to your computer and use it in GitHub Desktop.
Save vwochnik/0f15d1a04ecc7c5e92e4f0fce61870d3 to your computer and use it in GitHub Desktop.
Local Storage getter/setter with expiration
/**
* 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