Skip to content

Instantly share code, notes, and snippets.

@wjramos
Created August 29, 2017 23:15
Show Gist options
  • Save wjramos/69d279b7671e1ec324acff9b44042076 to your computer and use it in GitHub Desktop.
Save wjramos/69d279b7671e1ec324acff9b44042076 to your computer and use it in GitHub Desktop.
export default class Cache {
constructor(ttl = 300000) { // 5 Minutes
this.ttl = ttl;
this.expirations = new Map();
this.cache = new Map();
}
isExpired(key) {
return (!this.cache.has(key)) ||
(this.cache.has(key) && (!this.expirations.has(key) || this.expirations.get(key) < Date.now()));
}
set(key, val) {
if (this.isExpired(key)) {
this.cache.set(key, val);
this.expirations.set(key, Date.now() + this.ttl);
}
}
get(key) {
return this.cache.get(key);
}
has(key) {
return !this.isExpired(key) && this.cache.has(key);
}
delete(key) {
this.expire(key);
this.cache.delete(key);
}
clear() {
this.expireAll();
this.cache.clear();
}
expire(key) {
this.expirations.delete(key);
}
expireAll() {
this.expirations.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment