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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。