@chriscdn/memoize 1.0.10 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chriscdn/memoize",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "description": "Memoize a synchronous or asynchronous function.",
5
5
  "repository": "https://github.com/chriscdn/memoize",
6
6
  "author": "Christopher Meyer <chris@schwiiz.org>",
@@ -22,11 +22,14 @@
22
22
  "test": "vitest"
23
23
  },
24
24
  "dependencies": {
25
- "@chriscdn/promise-semaphore": "^3.0.1",
26
- "quick-lru": "^7.0.1"
25
+ "@chriscdn/promise-semaphore": "^3.1.2",
26
+ "quick-lru": "^7.3.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "microbundle": "^0.15.1",
30
- "vitest": "^3.2.4"
31
- }
30
+ "vitest": "^4.0.6"
31
+ },
32
+ "files": [
33
+ "lib"
34
+ ]
32
35
  }
@@ -1,201 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { Memoize, MemoizeAsync } from "../src/index";
3
-
4
- let addSyncCount = 0;
5
- let addAsyncCount = 0;
6
-
7
- const add = (x: number, y: number) => {
8
- addSyncCount += 1;
9
- return x + y;
10
- };
11
-
12
- const addAsync = async (x: number, y: number) => {
13
- addAsyncCount += 1;
14
- return x + y;
15
- };
16
-
17
- const _asyncThrowError = MemoizeAsync(async (x: number, y: number) => {
18
- addAsyncCount += 1;
19
- throw new Error("Boom!");
20
- return x + y;
21
- });
22
-
23
- const asyncThrowError = MemoizeAsync(async (x: number, y: number) => {
24
- try {
25
- await _asyncThrowError(x, y);
26
- } catch {
27
- return -1;
28
- }
29
- });
30
-
31
- describe("Memoization", () => {
32
- it("sync", async () => {
33
- const addCached = Memoize(add);
34
-
35
- expect(addCached(1, 2)).toBe(3);
36
- expect(addCached(1, 2)).toBe(3);
37
- expect(addCached(1, 2)).toBe(3);
38
- expect(addCached(1, 2)).toBe(3);
39
- expect(addCached(1, 2)).toBe(3);
40
-
41
- // different key here
42
- expect(addCached(2, 1)).toBe(3);
43
- expect(addSyncCount).toBe(2);
44
- });
45
-
46
- it("async", async () => {
47
- const addCachedAsync = MemoizeAsync(addAsync);
48
-
49
- await Promise.all([
50
- addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
51
- addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
52
- addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
53
- addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
54
-
55
- // different key here
56
- addCachedAsync(2, 1).then((value) => expect(value).toBe(3)),
57
- ]);
58
-
59
- expect(addAsyncCount).toBe(2);
60
- expect(addCachedAsync.cache.size).toBe(2);
61
- });
62
-
63
- it("resolver", () => {
64
- // This its the resolver function to ensure the same value is returned for
65
- // the same key.
66
-
67
- const addCachedSameKey = Memoize(add, { resolver: (x, y) => "key" });
68
-
69
- expect(addCachedSameKey(5, 7)).toBe(12);
70
- expect(addCachedSameKey(1, 1)).toBe(12);
71
- expect(addCachedSameKey(5, 1)).toBe(12);
72
- });
73
-
74
- it("async error", async () => {
75
- expect(await asyncThrowError(4, 3)).toBe(-1);
76
- });
77
- });
78
-
79
- describe("Memoization of Class methods", () => {
80
- class AddClass {
81
- count: number = 0;
82
-
83
- constructor() {
84
- this.add = Memoize(this.add.bind(this));
85
- }
86
-
87
- add(x: number, y: number) {
88
- this.count += 1;
89
- return x + y;
90
- }
91
- }
92
-
93
- it("Test1", () => {
94
- const obj = new AddClass();
95
-
96
- expect(obj.count).toBe(0);
97
- expect(obj.add(1, 2)).toBe(3);
98
- expect(obj.count).toBe(1);
99
- expect(obj.add(1, 2)).toBe(3);
100
- expect(obj.count).toBe(1);
101
- expect(obj.add(5, 2)).toBe(7);
102
- expect(obj.count).toBe(2);
103
- });
104
- });
105
-
106
- describe("Null & Undefined Cases", () => {
107
- const UndefinedFunc = Memoize((key: string) => undefined, {
108
- resolver: (key) => key,
109
- });
110
-
111
- const NullFunc = Memoize((key: string) => undefined, {
112
- resolver: (key) => key,
113
- });
114
-
115
- it("Undefined", () => {
116
- expect(UndefinedFunc.cache.has("hello")).toBe(false);
117
- expect(UndefinedFunc("hello")).toBe(undefined);
118
- expect(UndefinedFunc.cache.has("hello")).toBe(true);
119
- expect(UndefinedFunc("hello")).toBe(undefined);
120
- });
121
-
122
- it("Null", () => {
123
- expect(NullFunc.cache.has("hello")).toBe(false);
124
- expect(NullFunc("hello")).toBe(undefined);
125
- expect(NullFunc.cache.has("hello")).toBe(true);
126
- expect(NullFunc("hello")).toBe(undefined);
127
- });
128
- });
129
-
130
- describe("Object Reference", () => {
131
- const a = { hello: "world" };
132
-
133
- const funny = Memoize(() => a);
134
-
135
- it("Null", () => {
136
- expect(funny().hello).toBe("world");
137
- });
138
-
139
- it("Null", () => {
140
- a.hello = "mars";
141
- expect(funny().hello).toBe("mars");
142
- });
143
- });
144
-
145
- describe("ShouldCache", () => {
146
- const doNotCache = "do not cache";
147
-
148
- const myFunction = Memoize((word: string) => word, {
149
- shouldCache: (value) => value !== doNotCache,
150
- resolver: (value) => value,
151
- });
152
-
153
- myFunction("hi");
154
- myFunction(doNotCache);
155
-
156
- it("should be cached", () => {
157
- expect(myFunction.cache.has("hi")).toBe(true);
158
- });
159
-
160
- it("should not be cached", () => {
161
- expect(myFunction.cache.has(doNotCache)).toBe(false);
162
- });
163
- });
164
-
165
- describe("Do we need Memoize?", async () => {
166
- const myFunction = Memoize(async (word: string) => word, {
167
- resolver: (value) => value,
168
- });
169
-
170
- it("should be cached", async () => {
171
- expect(await myFunction("hi")).toBe("hi");
172
- });
173
-
174
- it("should be cached", async () => {
175
- expect(await myFunction("hi")).toBe("hi");
176
- });
177
-
178
- it("should be cached", async () => {
179
- expect(await myFunction("hi2")).toBe("hi2");
180
- });
181
-
182
- it("size", () => expect(myFunction.cache.size).toBe(2));
183
- });
184
-
185
- describe("Errors", async () => {
186
- const errorSync = Memoize(() => {
187
- throw new Error("errorsync");
188
- });
189
-
190
- const errorASync = Memoize(async () => {
191
- throw new Error("errorasync");
192
- });
193
-
194
- it("error sync", () => {
195
- expect(() => errorSync()).toThrowError("errorsync");
196
- });
197
-
198
- it("error async", () => {
199
- expect(errorASync()).rejects.toThrowError("errorasync");
200
- });
201
- });
package/src/index.ts DELETED
@@ -1,97 +0,0 @@
1
- import { Semaphore } from "@chriscdn/promise-semaphore";
2
- import QuickLRU from "quick-lru";
3
-
4
- const kDefaultMaxSize = 1000;
5
-
6
- type Options<T extends any[], Return> = {
7
- maxSize: number;
8
- maxAge?: number;
9
- shouldCache: (returnValue: Return, key: string) => boolean;
10
- resolver: (...args: T) => string;
11
- };
12
-
13
- /**
14
- * Memoize a synchronous function.
15
- */
16
- const Memoize = <Args extends unknown[], Return>(
17
- cb: (...args: Args) => Return,
18
- options: Partial<Options<Args, Return>> = {},
19
- ) => {
20
- const maxAge: number | undefined = options.maxAge;
21
- const maxSize = options.maxSize ?? kDefaultMaxSize;
22
- const shouldCache = options.shouldCache ?? (() => true);
23
-
24
- const resolver = options.resolver ??
25
- ((...args: Args) => JSON.stringify(args));
26
-
27
- const cache = new QuickLRU<string, Return>({
28
- maxAge,
29
- maxSize,
30
- });
31
-
32
- const memoizedFunction = (...args: Args): Return => {
33
- const key = resolver(...args);
34
-
35
- if (cache.has(key)) {
36
- return cache.get(key) as Return;
37
- } else {
38
- const returnValue = cb(...args);
39
- if (shouldCache(returnValue, key)) {
40
- cache.set(key, returnValue);
41
- }
42
- return returnValue;
43
- }
44
- };
45
-
46
- memoizedFunction.cache = cache;
47
-
48
- return memoizedFunction;
49
- };
50
-
51
- /**
52
- * Memoize an asynchronous function.
53
- */
54
- const MemoizeAsync = <Args extends unknown[], Return>(
55
- cb: (...args: Args) => Promise<Return>,
56
- options: Partial<Options<Args, Return>> = {},
57
- ) => {
58
- const maxAge: number | undefined = options.maxAge;
59
- const maxSize = options.maxSize ?? kDefaultMaxSize;
60
- const shouldCache = options.shouldCache ?? (() => true);
61
-
62
- const resolver = options.resolver ??
63
- ((...args: Args) => JSON.stringify(args));
64
-
65
- const cache = new QuickLRU<string, Return>({
66
- maxAge,
67
- maxSize,
68
- });
69
-
70
- const semaphore = new Semaphore();
71
-
72
- const memoizedFunction = async (...args: Args): Promise<Return> => {
73
- const key = resolver(...args);
74
-
75
- try {
76
- await semaphore.acquire(key);
77
-
78
- if (cache.has(key)) {
79
- return cache.get(key) as Return;
80
- } else {
81
- const returnValue = await cb(...args);
82
- if (shouldCache(returnValue, key)) {
83
- cache.set(key, returnValue);
84
- }
85
- return returnValue;
86
- }
87
- } finally {
88
- semaphore.release(key);
89
- }
90
- };
91
-
92
- memoizedFunction.cache = cache;
93
-
94
- return memoizedFunction;
95
- };
96
-
97
- export { Memoize, MemoizeAsync };