Last active
August 29, 2015 14:08
-
-
Save mahiya/5fb070e5cfe23098994b to your computer and use it in GitHub Desktop.
SessionStorageによるローカルキャッシュ
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 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