Skip to content

Instantly share code, notes, and snippets.

@rgrwkmn
Created January 28, 2016 16:54
Show Gist options
  • Select an option

  • Save rgrwkmn/9bd96cef3d40af93cd71 to your computer and use it in GitHub Desktop.

Select an option

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.
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