Refactor cache module
This commit is contained in:
+24
-28
@@ -1,52 +1,48 @@
|
||||
export type Cache<T> = Map<string, T>;
|
||||
export type AsyncCache<T> = Map<string, Promise<T>>;
|
||||
export type Cache<T> = Map<unknown, T>;
|
||||
|
||||
export function withCache<T, U extends (...args: any[]) => T>(
|
||||
callback: U,
|
||||
key: string,
|
||||
export function withCache<T, U extends (...args: Parameters<U>) => T>(
|
||||
fn: U,
|
||||
cache: Cache<T>,
|
||||
): (...args: Parameters<U>) => T {
|
||||
return (...args) => {
|
||||
): (key: unknown, ...args: Parameters<U>) => T {
|
||||
return (key, ...args) => {
|
||||
if (cache.has(key)) {
|
||||
return cache.get(key) as T;
|
||||
}
|
||||
|
||||
const value = callback(...args);
|
||||
const value = fn(...args);
|
||||
cache.set(key, value);
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
export function withAsyncCache<T, U extends (...args: any[]) => Promise<T>>(
|
||||
callback: U,
|
||||
key: string,
|
||||
cache: AsyncCache<T>,
|
||||
): (...args: Parameters<U>) => Promise<T> {
|
||||
return async (...args) => {
|
||||
export function withCacheAsync<
|
||||
T,
|
||||
U extends (...args: Parameters<U>) => Promise<T>,
|
||||
>(
|
||||
fn: U,
|
||||
cache: Cache<Promise<T>>,
|
||||
): (key: unknown, ...args: Parameters<U>) => Promise<T> {
|
||||
return async (key, ...args) => {
|
||||
if (cache.has(key)) {
|
||||
return (await cache.get(key)) as T;
|
||||
}
|
||||
|
||||
const value = callback(...args);
|
||||
const value = fn(...args);
|
||||
cache.set(key, value);
|
||||
|
||||
return await value;
|
||||
};
|
||||
}
|
||||
|
||||
export function useWithCache<T>(
|
||||
callback: (...args: any[]) => T,
|
||||
): [(uri: string) => T, Cache<T>] {
|
||||
const cache: Cache<T> = new Map();
|
||||
export function memoize<T, U>(fn: (arg: U) => T): [(arg: U) => T, Cache<T>] {
|
||||
const cache = new Map<unknown, T>();
|
||||
const callback = withCache(fn, cache);
|
||||
|
||||
return [(uri: string) => withCache(callback, uri, cache)(uri), cache];
|
||||
}
|
||||
|
||||
export function useWithAsyncCache<T>(
|
||||
callback: (...args: any[]) => Promise<T>,
|
||||
): [(uri: string) => Promise<T>, AsyncCache<T>] {
|
||||
const cache: AsyncCache<T> = new Map();
|
||||
|
||||
return [(uri: string) => withAsyncCache(callback, uri, cache)(uri), cache];
|
||||
return [
|
||||
(arg) => {
|
||||
return callback(arg, arg);
|
||||
},
|
||||
cache,
|
||||
];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user