|
1 | | -import { func_catch, func_remember } from "./func.ts"; |
| 1 | +import { func_catch, func_lazy, func_remember } from "./func.ts"; |
2 | 2 | import assert from "node:assert"; |
3 | 3 |
|
4 | 4 | Deno.test("func_remember", async () => { |
@@ -34,3 +34,43 @@ Deno.test("func_catch", async () => { |
34 | 34 | assert.deepEqual(await fn3(1, "2"), [undefined, `async 1+2`]); |
35 | 35 | assert.deepEqual(await fn4(1, "2"), [`async 1+2`, undefined]); |
36 | 36 | }); |
| 37 | + |
| 38 | +Deno.test("func_lazy", () => { |
| 39 | + let factoryCallCount = 0; |
| 40 | + |
| 41 | + const lazyFn = func_lazy(() => { |
| 42 | + factoryCallCount++; |
| 43 | + return (x: number) => x * 2; |
| 44 | + }); |
| 45 | + |
| 46 | + // Factory should not be called until first use |
| 47 | + assert.equal(factoryCallCount, 0); |
| 48 | + |
| 49 | + // First call should create the function |
| 50 | + assert.equal(lazyFn(5), 10); |
| 51 | + assert.equal(factoryCallCount, 1); |
| 52 | + |
| 53 | + // Subsequent calls should reuse the same function |
| 54 | + assert.equal(lazyFn(7), 14); |
| 55 | + assert.equal(factoryCallCount, 1); |
| 56 | +}); |
| 57 | + |
| 58 | +Deno.test("func_lazy with this context", () => { |
| 59 | + let factoryCallCount = 0; |
| 60 | + |
| 61 | + const lazyFn = func_lazy(() => { |
| 62 | + factoryCallCount++; |
| 63 | + return function (this: { multiplier: number }, x: number) { |
| 64 | + return x * this.multiplier; |
| 65 | + }; |
| 66 | + }); |
| 67 | + const obj = { multiplier: 3, fn: lazyFn }; |
| 68 | + |
| 69 | + // Test with this context |
| 70 | + assert.equal(obj.fn(5), 15); |
| 71 | + assert.equal(factoryCallCount, 1); |
| 72 | + |
| 73 | + // Should reuse the same function |
| 74 | + assert.equal(obj.fn(7), 21); |
| 75 | + assert.equal(factoryCallCount, 1); |
| 76 | +}); |
0 commit comments