-
Notifications
You must be signed in to change notification settings - Fork 28
/
memoize.test.ts
68 lines (56 loc) · 1.53 KB
/
memoize.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import memoize from "./memoize.ts";
import { assertEquals, assertThrows } from "testing/asserts.ts";
import { assertSpyCalls, spy } from "testing/mock.ts";
Deno.test("memoize", () => {
const root = spy((n: number) => Math.sqrt(n));
const memRoot = memoize(root);
assertEquals(memRoot(9), 3);
assertSpyCalls(root, 1);
assertEquals(memRoot(9), 3);
assertSpyCalls(root, 1);
assertEquals(memRoot(16), 4);
assertSpyCalls(root, 2);
assertEquals(memRoot(16), 4);
assertSpyCalls(root, 2);
memRoot.cache.clear();
assertEquals(memRoot(9), 3);
assertSpyCalls(root, 3);
assertEquals(memRoot(9), 3);
assertSpyCalls(root, 3);
const effect = spy((n: number) => n);
const eff = memoize(effect, { key: (n) => n, limit: 1 });
assertEquals(eff(1), 1);
assertSpyCalls(effect, 1);
assertEquals(eff(1), 1);
assertSpyCalls(effect, 1);
assertEquals(eff(2), 2);
assertSpyCalls(effect, 2);
assertEquals(eff(2), 2);
assertSpyCalls(effect, 2);
assertEquals(eff(1), 1);
assertSpyCalls(effect, 3);
assertEquals(eff(2), 2);
assertSpyCalls(effect, 4);
assertEquals(eff(1), 1);
assertSpyCalls(effect, 5);
assertEquals(eff(1), 1);
assertSpyCalls(effect, 5);
const mem = memoize((n: number) => Math.sqrt(n), {
key: (n) => n,
weak: true,
});
{
// @ts-expect-error
const _cache: Map<any, any> = mem.cache;
}
{
const _cache: Map<any, any> = memRoot.cache;
}
assertThrows(() =>
memoize((n: number) => Math.sqrt(n), {
key: (n) => n,
weak: true,
limit: 1,
})
);
});