scoped-cache.test.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { describe, expect, test } from "bun:test"
  2. import { createScopedCache } from "./scoped-cache"
  3. describe("createScopedCache", () => {
  4. test("evicts least-recently-used entry when max is reached", () => {
  5. const disposed: string[] = []
  6. const cache = createScopedCache((key) => ({ key }), {
  7. maxEntries: 2,
  8. dispose: (value) => disposed.push(value.key),
  9. })
  10. const a = cache.get("a")
  11. const b = cache.get("b")
  12. expect(a.key).toBe("a")
  13. expect(b.key).toBe("b")
  14. cache.get("a")
  15. const c = cache.get("c")
  16. expect(c.key).toBe("c")
  17. expect(cache.peek("a")?.key).toBe("a")
  18. expect(cache.peek("b")).toBeUndefined()
  19. expect(cache.peek("c")?.key).toBe("c")
  20. expect(disposed).toEqual(["b"])
  21. })
  22. test("disposes entries on delete and clear", () => {
  23. const disposed: string[] = []
  24. const cache = createScopedCache((key) => ({ key }), {
  25. dispose: (value) => disposed.push(value.key),
  26. })
  27. cache.get("a")
  28. cache.get("b")
  29. const removed = cache.delete("a")
  30. expect(removed?.key).toBe("a")
  31. expect(cache.peek("a")).toBeUndefined()
  32. cache.clear()
  33. expect(cache.peek("b")).toBeUndefined()
  34. expect(disposed).toEqual(["a", "b"])
  35. })
  36. test("expires stale entries with ttl and recreates on get", () => {
  37. let clock = 0
  38. let count = 0
  39. const disposed: string[] = []
  40. const cache = createScopedCache((key) => ({ key, count: ++count }), {
  41. ttlMs: 10,
  42. now: () => clock,
  43. dispose: (value) => disposed.push(`${value.key}:${value.count}`),
  44. })
  45. const first = cache.get("a")
  46. expect(first.count).toBe(1)
  47. clock = 9
  48. expect(cache.peek("a")?.count).toBe(1)
  49. clock = 11
  50. expect(cache.peek("a")).toBeUndefined()
  51. expect(disposed).toEqual(["a:1"])
  52. const second = cache.get("a")
  53. expect(second.count).toBe(2)
  54. expect(disposed).toEqual(["a:1"])
  55. })
  56. })