给lodash的memoize 增加expire过期功能

需求场景:对同一时间发起的大量重复参数相同的请求做缓存,但是在过了几秒钟之后就不需要缓存了,需要重新向服务器请求最新的数据

lodash.memoize方法会在整个页面的生命周期。需要增加一个超时功能

思路:类似于防抖函数,每次判断是否超过设置时间,超过就清空缓存列表

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版

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

例子 https://stackblitz.com/edit/j...

你可能感兴趣的:(给lodash的memoize 增加expire过期功能)