"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearMemoizedCache = exports.memoize = void 0;
/**
 * Create a cache key from an array of arguments
 * @param args
 * @returns
 */
const createCacheKeyFromArgs = (args) => args.reduce((cacheKey, arg) => (cacheKey += `_${typeof arg === "object" ? JSON.stringify(args) : String(arg)}_`), "");
let memoizedFnCache = {};
/**
 * Wrap a function into a memoized version of itself. Multiple calls for the same function
 * will return the same memoized function - thus enabling a shared cache of results.
 * `const memoizedItemSearch = memoize(searchItems);`
 * @param fn
 * @returns
 */
const memoize = (fn) => {
    if (!memoizedFnCache[`_${fn.name}`]) {
        const cache = {};
        const memoizedFn = (...args) => {
            const cacheKey = createCacheKeyFromArgs(args);
            if (cache[cacheKey]) {
                return cache[cacheKey];
            }
            const asyncFn = fn.call(undefined, ...args);
            cache[cacheKey] = asyncFn;
            return asyncFn;
        };
        memoizedFnCache[`_${fn.name}`] = memoizedFn;
    }
    return memoizedFnCache[`_${fn.name}`];
};
exports.memoize = memoize;
/**
 * Clear the cache of a memoized function
 * If no function name is provided, the entire cache is cleared
 * This is useful for testing, but should not be used in production
 * @param fn
 */
const clearMemoizedCache = (fnName) => {
    if (!fnName) {
        memoizedFnCache = {};
        return;
    }
    else {
        delete memoizedFnCache[`_${fnName}`];
    }
};
exports.clearMemoizedCache = clearMemoizedCache;
//# sourceMappingURL=memoize.js.map