File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 1
1
import { createSelectorQuery } from '@tarojs/taro'
2
+ import MiniLru from '@/utils/lru'
2
3
import { getRect , inBrowser } from './use-client-rect'
3
4
5
+ const lru = new MiniLru ( 10 )
6
+
4
7
export interface Rect {
5
8
dataset : Record < string , any >
6
9
id : string
@@ -30,10 +33,17 @@ export const getRectByTaro = async (element: any): Promise<Rect> => {
30
33
}
31
34
// 小程序下的逻辑
32
35
return new Promise ( ( resolve , reject ) => {
36
+ if ( lru . has ( element ) ) {
37
+ resolve ( lru . get ( element ) as Rect )
38
+ return
39
+ }
33
40
createSelectorQuery ( )
34
41
. select ( `#${ element . uid } ` )
35
42
. boundingClientRect ( )
36
43
. exec ( ( [ rects ] ) => {
44
+ if ( rects ) {
45
+ lru . set ( element , rects )
46
+ }
37
47
resolve ( rects )
38
48
} )
39
49
} )
Original file line number Diff line number Diff line change
1
+ export default class MiniLru {
2
+ private cache : Map < any , any >
3
+
4
+ private capacity : number
5
+
6
+ constructor ( capacity : number ) {
7
+ if ( capacity <= 0 ) {
8
+ throw new Error ( 'Cache capacity must be a positive number' )
9
+ }
10
+ this . cache = new Map ( )
11
+ this . capacity = capacity
12
+ }
13
+
14
+ get ( key : any ) : any | null {
15
+ if ( this . cache . has ( key ) ) {
16
+ const value = this . cache . get ( key )
17
+ this . cache . delete ( key )
18
+ this . cache . set ( key , value )
19
+ return value
20
+ }
21
+ return null
22
+ }
23
+
24
+ set ( key : any , value : any ) : void {
25
+ if ( this . cache . has ( key ) ) {
26
+ this . cache . delete ( key )
27
+ } else if ( this . cache . size >= this . capacity ) {
28
+ this . cache . delete ( this . cache . keys ( ) . next ( ) . value )
29
+ }
30
+ this . cache . set ( key , value )
31
+ }
32
+
33
+ has ( key : any ) : boolean {
34
+ return this . cache . has ( key )
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments