Open Rain120 opened 2 years ago
interface Config { resolver: (...args: any[]) => string; } const cache = new Map<string, any>(); function cache(config = {}) { return function(target: any, methodName: string, descriptor: PropertyDescriptor) { const originMethod = descriptor.value; descriptor.value = function(...args: any[]) { const key = config?.resolver ? resolver.apply(this, args) : JSON.stringify(args); if (cache.has(key)) { return cache.get(key); } const result = originMethod.apply(this, args); cache.set(key, result); return result; } } } function clear(key?: string) { if (key) { return cache.has(key) && cache.delete(key); } else if (cache) { return cache.clear(); } }
实现 Cache 装饰器,支持 clear