UNPKG

1.54 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.memoize = memoize;
7
8var _undefined = require("./is/undefined");
9
10var _stringify = require("./stringify");
11
12// Copyright 2017-2022 @polkadot/util authors & contributors
13// SPDX-License-Identifier: Apache-2.0
14function defaultGetId() {
15 return 'none';
16} // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
18
19function memoize(fn) {
20 let {
21 getInstanceId = defaultGetId
22 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
23 const cache = {};
24
25 const memoized = function () {
26 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
27 args[_key] = arguments[_key];
28 }
29
30 const stringParams = (0, _stringify.stringify)(args);
31 const instanceId = getInstanceId();
32
33 if (!cache[instanceId]) {
34 cache[instanceId] = {};
35 }
36
37 if ((0, _undefined.isUndefined)(cache[instanceId][stringParams])) {
38 cache[instanceId][stringParams] = fn(...args);
39 }
40
41 return cache[instanceId][stringParams];
42 };
43
44 memoized.unmemoize = function () {
45 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
46 args[_key2] = arguments[_key2];
47 }
48
49 const stringParams = (0, _stringify.stringify)(args);
50 const instanceId = getInstanceId();
51
52 if (cache[instanceId] && !(0, _undefined.isUndefined)(cache[instanceId][stringParams])) {
53 delete cache[instanceId][stringParams];
54 }
55 };
56
57 return memoized;
58}
\No newline at end of file