CyCache.ts 696 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. class CyCache {
  2. #data = new Map<string, any>();
  3. keyName = 'cy'
  4. maxSize = 1000;
  5. constructor(name: string) {
  6. this.keyName = name;
  7. }
  8. async get(key: string, cb: Function) {
  9. if (this.#data.size > this.maxSize) {
  10. this.#data.clear()
  11. }
  12. const k = this.keyName + '_' + key
  13. const temp = this.#data.get(k)
  14. if (temp) {
  15. return temp
  16. }
  17. const t = (await cb)(key)
  18. if (t !== null) {
  19. this.#data.set(k, t)
  20. }
  21. return t
  22. }
  23. setMaxSize(size: number) {
  24. this.maxSize = size;
  25. }
  26. clear() {
  27. this.#data.clear()
  28. }
  29. }
  30. export default CyCache