1import { describe, expect, it } from "vite-plus/test";
2import { LRUCache } from "./lruCache";
3
4describe("LRUCache", () => {
5 it("returns null for missing keys", () => {
6 const cache = new LRUCache<string>(2, 100);
7 expect(cache.get("missing")).toBeNull();
8 });
9
10 it("evicts oldest by max entries", () => {
11 const cache = new LRUCache<string>(2, 1_000);
12 cache.set("a", "A", 10);
13 cache.set("b", "B", 10);
14 cache.set("c", "C", 10);
15
16 expect(cache.get("a")).toBeNull();
17 expect(cache.get("b")).toBe("B");
18 expect(cache.get("c")).toBe("C");
19 });
20
21 it("promotes on get and evicts least recently used", () => {
22 const cache = new LRUCache<string>(2, 1_000);
23 cache.set("a", "A", 10);
24 cache.set("b", "B", 10);
25 expect(cache.get("a")).toBe("A");
26
27 cache.set("c", "C", 10);
28 expect(cache.get("a")).toBe("A");
29 expect(cache.get("b")).toBeNull();
30 expect(cache.get("c")).toBe("C");
31 });
32
33 it("evicts by memory budget", () => {
34 const cache = new LRUCache<string>(10, 25);
35 cache.set("a", "A", 10);
36 cache.set("b", "B", 10);
37 cache.set("c", "C", 10);
38
39 expect(cache.get("a")).toBeNull();
40 expect(cache.get("b")).toBe("B");
41 expect(cache.get("c")).toBe("C");
42 });
43
44 it("does not cache entries larger than the memory budget", () => {
45 const cache = new LRUCache<string>(2, 25);
46 cache.set("a", "A", 10);
47 cache.set("oversized", "X", 30);
48
49 expect(cache.get("a")).toBe("A");
50 expect(cache.get("oversized")).toBeNull();
51 });
52
53 it("preserves an existing entry when an oversized replacement is rejected", () => {
54 const cache = new LRUCache<string>(2, 25);
55 cache.set("a", "A", 10);
56 cache.set("a", "oversized", 30);
57
58 expect(cache.get("a")).toBe("A");
59 });
60});