Created
September 19, 2016 19:10
-
-
Save DroopyTersen/bb26348773d65a7c7c5c6e2e13c4a246 to your computer and use it in GitHub Desktop.
Supports localStorage or sessionStorage. Supports optional expiration. Supports regex key cache clearing
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 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