@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
30 lines (29 loc) • 932 B
JavaScript
import { jsonMemoSerializer, MapMemoCache } from './memo.util.js';
/**
* 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
*/
export function _memoFn(fn, opt = {}) {
const { logger = console, cacheFactory = () => new MapMemoCache(), cacheKeyFn = 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;
}