Skip to content

Instantly share code, notes, and snippets.

@a1xon
Created July 10, 2022 20:51
Show Gist options
  • Save a1xon/eb9f38c011acdf49293197c33d05043e to your computer and use it in GitHub Desktop.
Save a1xon/eb9f38c011acdf49293197c33d05043e to your computer and use it in GitHub Desktop.
Lightweight Cache
export class LighweightCache {
entries: CacheEntry[];
size: number;
ttl: number;
constructor(size: number, ttl: number) {
this.entries = [];
this.size = size;
this.ttl = ttl;
}
add(entry) {
if (this.entries.length >= this.size) {
this.entries.shift();
}
this.entries.push(entry);
}
clear() {
this.entries = [];
}
check(url: string): CacheResponse {
const now = Date.now();
const chachedEntry = this.entries.find(
(entry) => entry.url === url && entry.responseCode === 200 && now < entry.eol
);
if (chachedEntry) {
return new CacheResponse(true, chachedEntry);
} else {
/// return a new entry to insert a response into
const newEntry = new CacheEntry(url, this.ttl);
this.add(newEntry);
return new CacheResponse(false, newEntry);
}
}
}
class CacheEntry {
url: string;
eol: number;
responseCode: number;
responseData: Promise<object>;
constructor(url: string, ttl: number) {
this.url = url;
this.eol = Date.now() + ttl;
this.responseData = null;
this.responseCode = null;
}
}
class CacheResponse {
cached: boolean;
cacheEntry: CacheEntry;
constructor(cached: boolean, cacheEntry: CacheEntry) {
this.cached = cached;
this.cacheEntry = cacheEntry;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment