Skip to content

Instantly share code, notes, and snippets.

@joelalejandro
Last active June 8, 2020 15:37
Show Gist options
  • Save joelalejandro/11e92a440cde9f0b65d123816670f635 to your computer and use it in GitHub Desktop.
Save joelalejandro/11e92a440cde9f0b65d123816670f635 to your computer and use it in GitHub Desktop.
A proof-of-concept for an object-based cache with expiration control.
class Cache {
constructor() {
this._data = {};
}
read(key) {
const now = new Date().valueOf();
const { expiresAt, value } = this._data[key];
if (now >= expiresAt) {
this.delete(key);
return;
}
return this._data[key];
}
write(key, value, expires = 3600) {
const createdAt = new Date().valueOf();
const expiresAt = createdAt + expires * 1000;
this._data[key] = { createdAt, expiresAt, value };
setTimeout(() => this.delete(key), expires * 1000);
}
delete(key) {
delete this._data[key];
}
}
@joelalejandro
Copy link
Author

Note to all: this isn't production-ready, it's just something I wrote quickly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment