1 |
|
2 |
|
3 | import { stringify } from "./stringify.js";
|
4 |
|
5 | function defaultGetId() {
|
6 | return 'none';
|
7 | }
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export function memoize(fn, {
|
16 | getInstanceId = defaultGetId
|
17 | } = {}) {
|
18 | const cache = {};
|
19 |
|
20 | const memoized = (...args) => {
|
21 | const stringParams = stringify(args);
|
22 | const instanceId = getInstanceId();
|
23 |
|
24 | if (!cache[instanceId]) {
|
25 | cache[instanceId] = {};
|
26 | }
|
27 |
|
28 | if (cache[instanceId][stringParams] === undefined) {
|
29 | cache[instanceId][stringParams] = fn(...args);
|
30 | }
|
31 |
|
32 | return cache[instanceId][stringParams];
|
33 | };
|
34 |
|
35 | memoized.unmemoize = (...args) => {
|
36 | const stringParams = stringify(args);
|
37 | const instanceId = getInstanceId();
|
38 |
|
39 | if (cache[instanceId] && cache[instanceId][stringParams] !== undefined) {
|
40 | delete cache[instanceId][stringParams];
|
41 | }
|
42 | };
|
43 |
|
44 | return memoized;
|
45 | } |
\ | No newline at end of file |