Framework-free JavaScript TaskBuild a request cache with TTL and in-flight deduplication.
1type CacheEntry<T> = {
2 expiresAt: number;
3 value: Promise<T>;
4};
5
6const cache = new Map<string, CacheEntry<unknown>>();
7
8export async function cachedFetch<T>(
9 key: string,
10 load: () => Promise<T>,
11 ttlMs = 30_000,
12): Promise<T> {
13 const now = Date.now();
14 const hit = cache.get(key) as CacheEntry<T> | undefined;
15
16 if (hit && hit.expiresAt > now) return hit.value;
17
18 const value = load().catch((error) => {
AI InterviewerNotes
AICan you walk me through how your cache handles concurrent calls for the same key?
1:12 YouI’ll cache the promise so concurrent callers share the same request.
1:45 AIWhat should happen if the fetcher rejects?
2:10 Live evaluation4.2
4.0
4.6
EvidenceHandles concurrent callsLine 11–13
Stores in-flight promiseLine 14–16
Clears on settleLine 17–19