UNPKG

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