Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Created September 19, 2016 19:10
Show Gist options
  • Save DroopyTersen/bb26348773d65a7c7c5c6e2e13c4a246 to your computer and use it in GitHub Desktop.
Save DroopyTersen/bb26348773d65a7c7c5c6e2e13c4a246 to your computer and use it in GitHub Desktop.
Supports localStorage or sessionStorage. Supports optional expiration. Supports regex key cache clearing
var storage = localStorage;
var cache = {};
cache.setStorageType = function(localOrSessionStorage) {
storage = localOrSessionStorage
}
var _isExpired = function(cacheValue) {
return (cacheValue.expiration) && ((new Date()).getTime() > cacheValue.expiration);
};
cache.get = function(key) {
var valueStr = storage.getItem(key);
if (valueStr) {
var val = JSON.parse(valueStr);
return !_isExpired(val) ? val.payload : null
}
return null;
};
// takes in optional 'expires' which is a millisecond duration
cache.set = function(key, payload, expires) {
var value = { payload: payload };
if (expires) {
value.expiration = (new Date()).getTime() + expires;
}
storage.setItem(key, JSON.stringify(value));
return payload;
};
var _getAllKeys = function() {
var keys = [];
for ( var i = 0, len = storage.length; i < len; ++i ) {
keys.push(storage.key(i));
}
return keys;
};
cache.clear = function(keyOrFilterFunc) {
if (!keyOrFilterFunc) throw new Error("You must pass a key or a filter function");
if (typeof keyOrFilterFunc === "string") {
storage.removeItem(keyOrFilterFunc);
} else {
_getAllKeys()
.filter(keyOrFilterFunc)
.forEach(function(key) {
storage.removeItem(key);
})
}
};
module.exports = cache;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment