UNPKG

1.06 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { stringify } from "./stringify.js";
4
5function defaultGetId() {
6 return 'none';
7}
8/**
9 * @name memoize
10 * @description Memomize the function with a specific instanceId
11 */
12// eslint-disable-next-line @typescript-eslint/no-explicit-any
13
14
15export 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