|
|
|
@ -69,27 +69,58 @@ export function buildCachedRegFn<F extends (...args: any) => any>(
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据是否为 promise 做区分
|
|
|
|
|
const cachedGet: any = isPromise(get)
|
|
|
|
|
? async (...args: any) => {
|
|
|
|
|
if (isSame(args)) {
|
|
|
|
|
return _result;
|
|
|
|
|
} else {
|
|
|
|
|
const result = await get(...args);
|
|
|
|
|
_result = result ?? null;
|
|
|
|
|
_lastArgs = args;
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
: (...args: any) => {
|
|
|
|
|
if (isSame(args)) {
|
|
|
|
|
return _result;
|
|
|
|
|
} else {
|
|
|
|
|
const result = get(...args);
|
|
|
|
|
_result = result ?? null;
|
|
|
|
|
_lastArgs = args;
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
const cachedGet: any = (...args: any) => {
|
|
|
|
|
if (isSame(args)) {
|
|
|
|
|
return _result;
|
|
|
|
|
} else {
|
|
|
|
|
const result = get(...args);
|
|
|
|
|
_result = result ?? null;
|
|
|
|
|
_lastArgs = args;
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const refreshCache = () => {
|
|
|
|
|
_result = null;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const cachedSet = (fn: F) => {
|
|
|
|
|
set(fn);
|
|
|
|
|
refreshCache();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return [cachedGet, cachedSet, refreshCache];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 缓存版本的buildRegFn
|
|
|
|
|
* Promise 版本
|
|
|
|
|
*/
|
|
|
|
|
export function buildCachedRegFnAsync<F extends (...args: any) => any>(
|
|
|
|
|
name: string,
|
|
|
|
|
defaultFunc?: F
|
|
|
|
|
) {
|
|
|
|
|
const [get, set] = buildRegFn(name, defaultFunc);
|
|
|
|
|
|
|
|
|
|
let _result: any = null; // 缓存的返回值
|
|
|
|
|
let _lastArgs: any;
|
|
|
|
|
|
|
|
|
|
function isSame(args: any[]) {
|
|
|
|
|
// 当有缓存的返回值且两次参数一致
|
|
|
|
|
return _result !== null && _isEqual(args, _lastArgs);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据是否为 promise 做区分
|
|
|
|
|
const cachedGet: any = async (...args: any) => {
|
|
|
|
|
if (isSame(args)) {
|
|
|
|
|
return _result;
|
|
|
|
|
} else {
|
|
|
|
|
const result = await get(...args);
|
|
|
|
|
_result = result ?? null;
|
|
|
|
|
_lastArgs = args;
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const refreshCache = () => {
|
|
|
|
|
_result = null;
|
|
|
|
|