Skip to content

Commit

Permalink
feat(performance): getRectByTaro 方法在小程序内增加缓存以提升性能 (#2831)
Browse files Browse the repository at this point in the history
* feat: getRectByTaro 方法在小程序内增加缓存以提升性能

* feat: lock 文件提交

* feat: 工具类新增 lru

* feat:  增加capacity 参数值校验

* feat: lock 文件还原
  • Loading branch information
522109452 authored Jan 2, 2025
1 parent 9cfb6e9 commit be5dec0
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/utils/get-rect-by-taro.ts
Original file line number Diff line number Diff line change
@@ -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<string, any>
id: string
Expand Down Expand Up @@ -30,10 +33,17 @@ export const getRectByTaro = async (element: any): Promise<Rect> => {
}
// 小程序下的逻辑
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)
})
})
Expand Down
36 changes: 36 additions & 0 deletions src/utils/lru.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
export default class MiniLru {
private cache: Map<any, any>

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

0 comments on commit be5dec0

Please sign in to comment.