import { expect, test, vi } from "vitest"; import { type Cache, memoize, withCache } from "#/engine/lib/cache.ts"; test("withCache", () => { const cache: Cache = 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("async withCache", async () => { const cache: Cache> = new Map(); const fn = vi.fn(async (value: string): Promise => { return parseFloat(value); }); const callback = withCache(fn, cache); const one = "1"; const res = await callback("one", one); const _ = await callback("one", one); expect(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 => { return parseFloat(value); }); const [callback, cache] = memoize(fn); const one = "1"; const res = await callback(one); const _ = await callback(one); expect(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); });