foxts
Version:
Opinionated collection of common TypeScript utils by @SukkaW
2 lines (1 loc) • 1.23 kB
JavaScript
import{fastStringArrayJoin as e}from"./fast-string-array-join.mjs";import{identity as a}from"./identity.mjs";import{noop as t}from"./noop.mjs";function i(i,{onlyUseCachedIfFail:r=!1,resetTtlOnHit:n=!1,defaultTtl:l=6048e5,onCacheUpdate:s=t,onCacheMiss:m=t,onCacheHit:o=t,keyHasher:f=a,argHasher:u}){return function(t,h){if(h?.temporaryBypass)return(...e)=>Promise.resolve(t(...e));let d=h&&"serializer"in h?h.serializer:a,c=h&&"deserializer"in h?h.deserializer:a,p=h?.ttl??l,w=t.toString(),y=f(w);return async function(...a){let l=e(await Promise.all([y,u(a)]),"|"),f=t.name||w||l,h=i.get(l);if(h&&"object"==typeof h&&"then"in h&&(h=await h),r)try{let e=await t(...a);s(l,{humanReadableName:f,isUseCachedIfFail:!0});let r=i.set(l,d(e),p);return r&&"then"in r&&await r,e}catch(e){if(null==h)throw m(l,{humanReadableName:f,isUseCachedIfFail:!0}),e;if(n){let e=i.updateTtl?.(l,p);e&&"then"in e&&await e}return o(l,{humanReadableName:f,isUseCachedIfFail:!0}),c(h)}if(null==h){m(l,{humanReadableName:f,isUseCachedIfFail:!1});let e=await t(...a),r=i.set(l,d(e),p);return r&&"then"in r&&await r,e}if(o(l,{humanReadableName:f,isUseCachedIfFail:!1}),n){let e=i.updateTtl?.(l,p);e&&"then"in e&&await e}return c(h)}}}export{i as createMemoize};