File tree Expand file tree Collapse file tree 2 files changed +25
-0
lines changed Expand file tree Collapse file tree 2 files changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -49,6 +49,8 @@ Step 2. Add the dependency
49
49
50
50
<summary >展开查看</summary >
51
51
52
+ https://leetcode.cn/problems/memoize-ii/
53
+
52
54
https://leetcode.cn/problems/cache-with-time-limit/
53
55
54
56
https://leetcode.cn/problems/sleep
Original file line number Diff line number Diff line change
1
+ type Fn = ( ...params : any ) => any ;
2
+
3
+ function memoize ( fn : Fn ) : Fn {
4
+ const cache = new Map < string , any > ( ) ;
5
+ let index = 0 ;
6
+ const pointers = new Map < any , number > ( ) ;
7
+
8
+ return function ( ...args : any [ ] ) {
9
+ const key = JSON . stringify ( args . map ( ( a : any ) => {
10
+ const pointer : number = pointers . get ( a ) ?? index ++ ;
11
+ pointers . set ( a , pointer ) ;
12
+ return pointer ;
13
+ } ) ) ;
14
+
15
+ const value = cache . get ( key ) ?? fn ( ...args ) ;
16
+ cache . set ( key , value ) ;
17
+
18
+ return value ;
19
+ } ;
20
+ }
21
+
22
+ export type { Fn } ;
23
+ export default memoize ;
You can’t perform that action at this time.
0 commit comments