File tree Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change @@ -491,3 +491,24 @@ BSD April 12, 2003 BSD`)
491
491
) . toMatchSnapshot ( )
492
492
} )
493
493
} )
494
+
495
+ describe ( 'memorize' , ( ) => {
496
+ it ( 'memorizes a function' , async ( ) => {
497
+ const fnRaw = jest . fn ( async args => args )
498
+ const arg1 = { one : '1' }
499
+ const arg2 = { another : { word : 'word' } }
500
+ const fnMemorized = sh . memorize ( fnRaw )
501
+
502
+ const arg1CallResult1 = await fnMemorized ( arg1 )
503
+ const arg1CallResult2 = await fnMemorized ( arg1 )
504
+
505
+ const arg2CallResult1 = await fnMemorized ( arg2 )
506
+ const arg2CallResult2 = await fnMemorized ( arg2 )
507
+
508
+ expect ( fnRaw ) . toHaveBeenCalledTimes ( 2 )
509
+ expect ( fnRaw ) . toHaveBeenCalledWith ( arg2 )
510
+
511
+ expect ( arg1CallResult1 ) . toBe ( arg1CallResult2 )
512
+ expect ( arg2CallResult1 ) . toBe ( arg2CallResult2 )
513
+ } )
514
+ } )
Original file line number Diff line number Diff line change @@ -27,7 +27,7 @@ export function execShellScript(body: string): Promise<string> {
27
27
/**
28
28
* Get documentation for the given word by usingZZ help and man.
29
29
*/
30
- export async function getShellDocumentation ( {
30
+ export async function getShellDocumentationWithoutCache ( {
31
31
word,
32
32
} : {
33
33
word : string
@@ -84,3 +84,27 @@ export function formatManOutput(manOutput: string): string {
84
84
85
85
return formattedManOutput
86
86
}
87
+
88
+ /**
89
+ * Only works for one-parameter (serializable) functions.
90
+ */
91
+ export function memorize < T extends Function > ( func : T ) : T {
92
+ const cache = new Map ( )
93
+
94
+ const returnFunc = async function ( arg : any ) {
95
+ const cacheKey = JSON . stringify ( arg )
96
+
97
+ if ( cache . has ( cacheKey ) ) {
98
+ return cache . get ( cacheKey )
99
+ }
100
+
101
+ const result = await func ( arg )
102
+
103
+ cache . set ( cacheKey , result )
104
+ return result
105
+ }
106
+
107
+ return returnFunc as any
108
+ }
109
+
110
+ export const getShellDocumentation = memorize ( getShellDocumentationWithoutCache )
You can’t perform that action at this time.
0 commit comments