Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Last active August 31, 2020 18:09
Show Gist options
  • Select an option

  • Save PatrickJS/9a18e63ae61b7d38ed09b3b65d7c2dcc to your computer and use it in GitHub Desktop.

Select an option

Save PatrickJS/9a18e63ae61b7d38ed09b3b65d7c2dcc to your computer and use it in GitHub Desktop.
this doesn't work in cloudflare workers where time doesn't change
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