ahooks
Version:
react hooks library
39 lines (38 loc) • 1.12 kB
JavaScript
const cache = new Map();
const clearTimer = (cachedData) => {
if (cachedData === null || cachedData === void 0 ? void 0 : cachedData.timer) {
clearTimeout(cachedData.timer);
}
};
const setCache = (key, cacheTime, cachedData) => {
const currentCache = cache.get(key);
clearTimer(currentCache);
let timer = undefined;
if (cacheTime > -1) {
// if cache out, clear it
timer = setTimeout(() => {
cache.delete(key);
}, cacheTime);
}
cache.set(key, Object.assign(Object.assign({}, cachedData), { timer }));
};
const getCache = (key) => {
return cache.get(key);
};
const clearCache = (key) => {
if (key) {
const cacheKeys = Array.isArray(key) ? key : [key];
cacheKeys.forEach((cacheKey) => {
const currentCache = cache.get(cacheKey);
clearTimer(currentCache);
cache.delete(cacheKey);
});
}
else {
for (const currentCache of cache.values()) {
clearTimer(currentCache);
}
cache.clear();
}
};
export { getCache, setCache, clearCache };