-
-
Save Kaligraphy247/2703e5dd1276d8fbd1f615b2e316f08f to your computer and use it in GitHub Desktop.
Simple Typescript Memory Cache
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 const cache = { | |
data: new Map(), | |
timers: new Map(), | |
set: (k: string, v: any, ttl: number) => { | |
if (cache.timers.has(k)) { | |
clearTimeout(cache.timers.get(k)) | |
} | |
cache.timers.set( | |
k, | |
setTimeout(() => cache.delete(k), ttl * 1000) | |
) | |
cache.data.set(k, v) | |
}, | |
get: (k: string) => cache.data.get(k), | |
has: (k: string) => cache.data.has(k), | |
delete: (k: string) => { | |
if (cache.timers.has(k)) { | |
clearTimeout(cache.timers.get(k)) | |
} | |
cache.timers.delete(k) | |
return cache.data.delete(k) | |
}, | |
clear: () => { | |
cache.data.clear() | |
for (const v of cache.timers.values()) { | |
clearTimeout(v) | |
} | |
cache.timers.clear() | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment