observation-js
Version:
A fully-typed TypeScript client for the waarneming.nl API.
28 lines (27 loc) • 692 B
JavaScript
export class InMemoryCache {
#cache = new Map();
get(key) {
const entry = this.#cache.get(key);
if (!entry)
return undefined;
if (entry.expires > Date.now()) {
return entry.data;
}
// Clean up expired entry
this.#cache.delete(key);
return undefined;
}
set(key, value, ttl) {
this.#cache.set(key, {
data: value,
expires: Date.now() + ttl * 1000,
});
}
delete(key) {
this.#cache.delete(key);
}
has(key) {
// We check `get` to make sure we don't say we "have" an expired key
return this.get(key) !== undefined;
}
}