diff --git a/src/utils/get-rect-by-taro.ts b/src/utils/get-rect-by-taro.ts index cf3abd59df..f18924349d 100644 --- a/src/utils/get-rect-by-taro.ts +++ b/src/utils/get-rect-by-taro.ts @@ -1,6 +1,9 @@ import { createSelectorQuery } from '@tarojs/taro' +import MiniLru from '@/utils/lru' import { getRect, inBrowser } from './use-client-rect' +const lru = new MiniLru(10) + export interface Rect { dataset: Record id: string @@ -30,10 +33,17 @@ export const getRectByTaro = async (element: any): Promise => { } // 小程序下的逻辑 return new Promise((resolve, reject) => { + if (lru.has(element)) { + resolve(lru.get(element) as Rect) + return + } createSelectorQuery() .select(`#${element.uid}`) .boundingClientRect() .exec(([rects]) => { + if (rects) { + lru.set(element, rects) + } resolve(rects) }) }) diff --git a/src/utils/lru.ts b/src/utils/lru.ts new file mode 100644 index 0000000000..1d9cca3381 --- /dev/null +++ b/src/utils/lru.ts @@ -0,0 +1,36 @@ +export default class MiniLru { + private cache: Map + + private capacity: number + + constructor(capacity: number) { + if (capacity <= 0) { + throw new Error('Cache capacity must be a positive number') + } + this.cache = new Map() + this.capacity = capacity + } + + get(key: any): any | null { + if (this.cache.has(key)) { + const value = this.cache.get(key) + this.cache.delete(key) + this.cache.set(key, value) + return value + } + return null + } + + set(key: any, value: any): void { + if (this.cache.has(key)) { + this.cache.delete(key) + } else if (this.cache.size >= this.capacity) { + this.cache.delete(this.cache.keys().next().value) + } + this.cache.set(key, value) + } + + has(key: any): boolean { + return this.cache.has(key) + } +}