Skip to content

Instantly share code, notes, and snippets.

@mahiya
Last active August 29, 2015 14:08
Show Gist options
  • Save mahiya/5fb070e5cfe23098994b to your computer and use it in GitHub Desktop.
Save mahiya/5fb070e5cfe23098994b to your computer and use it in GitHub Desktop.
SessionStorageによるローカルキャッシュ
var localCache = {
get: function(key, getMethod, cacheMs) {
if(!cacheMs) cacheMs = this._defaultCacheMs;
var cache = sessionStorage.getItem(key);
if(cache == null) {
return this._setAndGet(key, getMethod, cacheMs);
}
var data = JSON.parse(cache);
if(new Date() > new Date(data.expire)) {
return this._setAndGet(key, getMethod, cacheMs);
}
return data.value;
},
_defaultCacheMs: 1000 * 60,
_setAndGet: function(key, getMethod, cacheMs) {
if(!getMethod)return null;
sessionStorage.setItem(key, JSON.stringify({
value :getMethod(),
expire : new Date(new Date().getTime() + cacheMs).getTime(),
}));
return this.get(key);
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment