Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(performance): getRectByTaro 方法在小程序内增加缓存以提升性能 #2831

Merged
merged 6 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Alex-huxiyang marked this conversation as resolved.
Show resolved Hide resolved

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