关于javascript:给lodash的memoize-增加expire过期功能

47次阅读

共计 780 个字符,预计需要花费 2 分钟才能阅读完成。

需要场景:对同一时间发动的大量反复参数雷同的申请做缓存,然而在过了几秒钟之后就不须要缓存了,须要从新向服务器申请最新的数据

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 = <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
  }
}

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

正文完
 0