Created
December 10, 2018 16:30
-
-
Save ericwenn/baa058fd9e02d8ea09707812f52c66e6 to your computer and use it in GitHub Desktop.
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
interface Cache<T> { | |
get: (id: string) => T | null; | |
set: (id: string, item: T) => void; | |
invalidate: (id: string) => void; | |
}; | |
interface CacheEntry<T> { | |
// Unix timestamp Math.floor(new Date() / 1000) | |
cachedAt: number; | |
item: T; | |
}; | |
interface CacheMap<T> { | |
[key: string]: CacheEntry<T> | |
}; | |
interface CacheOptions { | |
// In seconds | |
TTL: number | |
}; | |
const createCache<T> = ({ TTL }: CacheOptions): Cache<T> => { | |
return { | |
_cache: CacheMap<T> = {}, | |
get: function(id:string) { | |
const entry = this._cache[id]; | |
if (!entry) { | |
return null; | |
} | |
const now = Math.floor(new Date() / 1000); | |
if (now - entry.cachedAt > TTL) { | |
this.invalidate(id); | |
return null; | |
} | |
return entry.item; | |
}, | |
invalidate(id: string) { | |
if (this._cache[id]) { | |
delete this._cache[id]; | |
} | |
}, | |
set(id: string, item: T) { | |
const now = Math.floor(new Date() / 1000); | |
this._cache[id] = { | |
cachedAt: now, | |
item | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment