@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
33 lines (32 loc) • 1.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports._memoFn = _memoFn;
const memo_util_1 = require("./memo.util");
/**
* Only supports Sync functions.
* To support Async functions - use _memoFnAsync.
* Technically, you can use it with Async functions, but it'll return the Promise without awaiting it.
*
* @experimental
*/
function _memoFn(fn, opt = {}) {
const { logger = console, cacheFactory = () => new memo_util_1.MapMemoCache(), cacheKeyFn = memo_util_1.jsonMemoSerializer, } = opt;
const cache = cacheFactory();
const memoizedFn = function (...args) {
const ctx = this;
const cacheKey = cacheKeyFn(args);
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
const value = fn.apply(ctx, args);
try {
cache.set(cacheKey, value);
}
catch (err) {
logger.error(err);
}
return value;
};
Object.assign(memoizedFn, { cache });
return memoizedFn;
}