Last active
June 8, 2020 15:37
-
-
Save joelalejandro/11e92a440cde9f0b65d123816670f635 to your computer and use it in GitHub Desktop.
A proof-of-concept for an object-based cache with expiration control.
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._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]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note to all: this isn't production-ready, it's just something I wrote quickly.