UNPKG

2.54 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.Memoize = Memoize;
4// eslint-disable-next-line @typescript-eslint/no-explicit-any
5var cacheProp = Symbol.for('[memoize]');
6/**
7 * @internal
8 */
9// eslint-disable-next-line @typescript-eslint/no-explicit-any
10function Memoize(keyBuilder) {
11 // eslint-disable-next-line @typescript-eslint/no-explicit-any
12 return function (_, propertyKey, descriptor) {
13 if (descriptor.value != null) {
14 // eslint-disable-next-line @typescript-eslint/no-explicit-any
15 descriptor.value = memoize(propertyKey, descriptor.value, keyBuilder || (function (v) { return v; }));
16 }
17 else if (descriptor.get != null) {
18 descriptor.get = memoize(propertyKey, descriptor.get, keyBuilder || (function () { return propertyKey; }));
19 }
20 };
21}
22// See https://github.com/microsoft/TypeScript/issues/1863#issuecomment-579541944
23// eslint-disable-next-line @typescript-eslint/no-explicit-any
24function ensureCache(target, reset) {
25 if (reset === void 0) { reset = false; }
26 if (reset || !target[cacheProp]) {
27 Object.defineProperty(target, cacheProp, {
28 value: Object.create(null),
29 configurable: true,
30 });
31 }
32 return target[cacheProp];
33}
34// See https://github.com/microsoft/TypeScript/issues/1863#issuecomment-579541944
35// eslint-disable-next-line @typescript-eslint/no-explicit-any
36function ensureChildCache(target, key, reset) {
37 if (reset === void 0) { reset = false; }
38 var dict = ensureCache(target);
39 if (reset || !dict[key]) {
40 // eslint-disable-next-line @typescript-eslint/no-explicit-any
41 dict[key] = new Map();
42 }
43 // eslint-disable-next-line @typescript-eslint/no-explicit-any
44 return dict[key];
45}
46function memoize(namespace,
47// eslint-disable-next-line @typescript-eslint/no-explicit-any
48func,
49// eslint-disable-next-line @typescript-eslint/no-explicit-any
50keyBuilder) {
51 // eslint-disable-next-line @typescript-eslint/no-explicit-any
52 return function () {
53 var args = [];
54 for (var _i = 0; _i < arguments.length; _i++) {
55 args[_i] = arguments[_i];
56 }
57 var cache = ensureChildCache(this, namespace);
58 var key = keyBuilder.apply(this, args);
59 if (cache.has(key))
60 return cache.get(key);
61 // eslint-disable-next-line @typescript-eslint/no-explicit-any
62 var res = func.apply(this, args);
63 cache.set(key, res);
64 return res;
65 };
66}