Last active
August 31, 2020 18:09
-
-
Save PatrickJS/9a18e63ae61b7d38ed09b3b65d7c2dcc to your computer and use it in GitHub Desktop.
this doesn't work in cloudflare workers where time doesn't change
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
| export class ExpireMap extends Map { | |
| expiring = new Map() | |
| constructor(private _millis: number, private _getTime = this._getTime) { | |
| super() | |
| } | |
| public set<T, V>(key: T, value: V): V { | |
| const expire = this.getTime() + this._millis | |
| this.expiring.set(key, expire) | |
| super.set(key, value) | |
| return value | |
| } | |
| public get<T, V>(key: T): V | undefined { | |
| const time = this.getTime() | |
| this.expiring.forEach((exp, _key) => { | |
| if (exp < time) super.delete(_key) | |
| }) | |
| return super.get(key) | |
| } | |
| private _getTime() { | |
| return new Date().getTime() | |
| } | |
| } | |
| export default ExpireMap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment