Refactor cache module

This commit is contained in:
Schluffe
2026-08-08 14:00:36 +02:00
parent bb071074d2
commit bed4a58cad
7 changed files with 249 additions and 118 deletions
+93
View File
@@ -0,0 +1,93 @@
import { expect, test, vi } from "vitest";
import {
type Cache,
memoize,
withCache,
withCacheAsync,
} from "#/engine/lib/cache.ts";
test("withCache", () => {
const cache: Cache<number> = new Map();
const fn = vi.fn((value: string): number => {
return parseFloat(value);
});
const callback = withCache(fn, cache);
const one = "1";
const res = callback("one", one);
const _ = callback("one", one);
expect(res).toBe(1);
expect(fn).toHaveBeenCalledTimes(1);
expect(callback(2, "2.0")).toBe(2);
expect(fn).toHaveBeenCalledTimes(2);
cache.clear();
expect(callback("one", "1")).toBe(1);
expect(fn).toHaveBeenCalledTimes(3);
});
test("withCacheAsync", async () => {
const cache: Cache<Promise<number>> = new Map();
const fn = vi.fn(async (value: string): Promise<number> => {
return parseFloat(value);
});
const callback = withCacheAsync(fn, cache);
const one = "1";
const res = callback("one", one);
const _ = callback("one", one);
expect(await res).toBe(1);
expect(fn).toHaveBeenCalledTimes(1);
expect(await callback("two", "2")).toBe(2);
expect(fn).toHaveBeenCalledTimes(2);
cache.clear();
expect(await callback("one", "1")).toBe(1);
expect(fn).toHaveBeenCalledTimes(3);
});
test("memoize", () => {
const fn = vi.fn((value: string): number => {
return parseFloat(value);
});
const [callback, cache] = memoize(fn);
const one = "1";
const res = callback(one);
const _ = callback(one);
expect(res).toBe(1);
expect(fn).toHaveBeenCalledTimes(1);
expect(callback("2.0")).toBe(2);
expect(fn).toHaveBeenCalledTimes(2);
cache.clear();
expect(callback("1")).toBe(1);
expect(fn).toHaveBeenCalledTimes(3);
});
test("async memoize", async () => {
const fn = vi.fn(async (value: string): Promise<number> => {
return parseFloat(value);
});
const [callback, cache] = memoize(fn);
const one = "1";
const res = callback(one);
const _ = callback(one);
expect(await res).toBe(1);
expect(fn).toHaveBeenCalledTimes(1);
expect(await callback("2.0")).toBe(2);
expect(fn).toHaveBeenCalledTimes(2);
cache.clear();
expect(await callback("1")).toBe(1);
expect(fn).toHaveBeenCalledTimes(3);
});