Demand scenario: Cache a large number of repeated requests with the same parameters initiated at the same time, but after a few seconds, there is no need to cache, and you need to request the latest data from the server again

The lodash.memoize method will be used throughout the life cycle of the page. Need to add a timeout function

Idea: Similar to the anti-shake function, every time it is judged whether the set time is exceeded, the cache list is cleared if it exceeds

const myMemoize = (fn, duration = 2000) => {
  let t = new Date().getTime();
  const memoized = _.memoize(fn, (...args) => JSON.stringify(args));
  return (...args) => {
    const curr = new Date().getTime();
    if (curr - t > duration) {
      memoized.cache = new _.memoize.Cache();
      t = curr;
    }
    return memoized(...args);
  };
};

ts version

export const myMemoize = <T extends (...args: any[]) => Promise<any>, R = ReturnType<T>>(fn: T, duration = 2000) => {
  let t = new Date().getTime()
  const memoized = memoize(fn,(...args: Parameters<T>) => JSON.stringify(args))
  return (...args: Parameters<T>) => {
    const curr = new Date().getTime()
    if(curr - t > duration) {
      memoized.cache = new memoize.Cache
      t = curr
    }
    return memoized(...args) as unknown as R
  }
}

Example https://stackblitz.com/edit/memoize-expire?file=index.js


阿古达木
574 声望17 粉丝

牛逼的工程师就是能用简单的代码和思路写出复杂的功能