UNPKG

1.12 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.memoize = void 0;
4const stringify_js_1 = require("./stringify.js");
5function defaultGetId() {
6 return 'none';
7}
8/**
9 * @name memoize
10 * @description Memomize the function with a specific instanceId
11 */
12function memoize(fn, { getInstanceId = defaultGetId } = {}) {
13 const cache = {};
14 const memoized = (...args) => {
15 const stringParams = (0, stringify_js_1.stringify)(args);
16 const instanceId = getInstanceId();
17 if (!cache[instanceId]) {
18 cache[instanceId] = {};
19 }
20 if (cache[instanceId][stringParams] === undefined) {
21 cache[instanceId][stringParams] = fn(...args);
22 }
23 return cache[instanceId][stringParams];
24 };
25 memoized.unmemoize = (...args) => {
26 const stringParams = (0, stringify_js_1.stringify)(args);
27 const instanceId = getInstanceId();
28 if (cache[instanceId]?.[stringParams] !== undefined) {
29 delete cache[instanceId][stringParams];
30 }
31 };
32 return memoized;
33}
34exports.memoize = memoize;