Rain120 / Web-Study

日常学习,工作写的笔记
66 stars 108 forks source link

Typescript 实现 Cache 装饰器 #22

Open Rain120 opened 2 years ago

Rain120 commented 2 years ago

实现 Cache 装饰器,支持 clear

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();
  }
}