Frame · dsa / ai-algorithms / 13-lru-semantic-cache.jsJavaScript
LRU Semantic Cache With a Similarity Threshold
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
LRU Semantic Cache With a Similarity Threshold
Problem: A semantic cache returns a stored LLM response when a new prompt's
embedding is close enough to a previous one, saving latency and cost.
Implement `SemanticCache({ capacity, threshold })`:
- `set(embedding, value)`: store an entry as most recently used. If an
existing entry has cosine similarity >= 0.9999 (effectively the same
prompt) overwrite it instead. If size exceeds capacity, evict the least
recently used entry.
- `get(embedding)`: find the stored entry with the highest cosine
similarity. If it is >= threshold, mark it most recently used and return
`{ value, similarity }`; otherwise return null (a miss does not change
recency).
- `size` getter.
Constraints:
- 1 <= capacity <= 10^4, -1 <= threshold <= 1
Example:
cache(capacity 2, threshold 0.9)
set([1,0], "A"); set([0,1], "B")
get([0.99, 0.1]) -> { value: "A", similarity ~0.995 }
set([1,1], "C") evicts "B" (least recently used)
Approach: A JavaScript Map preserves insertion order, so deleting and
re-inserting a key moves it to the most-recent end and the first key is
the LRU victim. Lookup is a linear similarity scan (swap in an ANN index
for large caches). get/set are O(capacity * d) time, space O(capacity * d).
@param {{ capacity: number, threshold: number }} opts