Created
January 28, 2016 16:54
-
-
Save rgrwkmn/9bd96cef3d40af93cd71 to your computer and use it in GitHub Desktop.
Simple JS cache class. Use cache.get to get the value of a key from the cache and provide a function for getting what should be there if it doesn't exist yet or the cache has expired.
This file contains hidden or 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
| class Cache { | |
| constructor() { | |
| this.cache = {}; | |
| this.timeouts = {}; | |
| } | |
| set(key, value, ttl) { | |
| this.cache[key] = value; | |
| if (ttl) { | |
| // instead of using timeouts it could validate the ttl when `get` is called | |
| // so the amount of timeouts doesn't get out of control | |
| if (this.timeouts[key]) { | |
| clearTimeout(this.timeouts[key]); | |
| } | |
| this.timeouts[key] = setTimeout(() => { | |
| delete this.cache[key]; | |
| }, ttl); | |
| } | |
| } | |
| get(key, ifUndefined, ttl) { | |
| var val = this.cache[key]; | |
| if (!val && typeof ifUndefined === 'function') { | |
| this.set(key, ifUndefined(), ttl); | |
| } | |
| return this.cache[key]; | |
| } | |
| } | |
| export default function() { | |
| return new Cache(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment