Skip to content

Instantly share code, notes, and snippets.

@valerykalashnikov
Last active August 29, 2015 13:57
Show Gist options
  • Save valerykalashnikov/9547789 to your computer and use it in GitHub Desktop.
Save valerykalashnikov/9547789 to your computer and use it in GitHub Desktop.
LocalStorageCache
var cache = (function() {
'use strict';
var TTL_POSTFIX = 'time2live';
var TTE_POSTFIX = 'time2expire';
function _hasLocalStorage() {
if (!window.localStorage) {
throw new Error('you have no localStorage');
}
}
function _removeCachedKey(key) {
localStorage.removeItem(key);
localStorage.removeItem(key+TTE_POSTFIX);
localStorage.removeItem(key+TTL_POSTFIX);
}
function addItem(key,value,expireAfter,removeAfter) {
_hasLocalStorage();
localStorage.setItem(key,value);
if (expireAfter > removeAfter) {
throw new Error('Expire after have to be less then removeAfter');
}
localStorage.setItem(key+TTE_POSTFIX, +new Date() + 1000 * 60 * 60 * expireAfter);
localStorage.setItem(key+TTL_POSTFIX, +new Date() + 1000 * 60 * 60 * removeAfter);
}
function getItem(key) {
_hasLocalStorage();
var ttl = parseInt(localStorage.getItem(key+TTL_POSTFIX));
var tte = parseInt(localStorage.getItem(key+TTE_POSTFIX));
var value = localStorage.getItem(key);
if (+new Date() > tte) {
return {value: value, expired: false};
}
else if (+new Date() < ttl) {
return {value:value, expired: true};
}
else {
_removeCachedKey(key);
return null;
}
}
return {
addItem:addItem,
getItem:getItem
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment