-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02623-memoize.ts
31 lines (27 loc) · 1 KB
/
02623-memoize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* medium :: typescript */
/*
Memoizes a given function to cache results for unique inputs, avoiding redundant
computations. Supports `sum`, `fib`, and `factorial` functions as inputs.
- - - -
Time :: O(N) :: 289ms
Space :: O(U) :: 86.76MB
*/
type Sum = ( a: number, b: number ) => number;
type Fib = ( n: number ) => number;
type Factorial = ( n: number ) => number;
type Fn = Sum & Fib & Factorial;
// Solution entrypoint :: - - - -
function memoize( fn: Fn ): Fn
{
const cache: Map<string, ReturnType<Fn>> = new Map();
return function ( ...args: Parameters<Fn> ): ReturnType<Fn>
{
const key: string = args.join( ',' );
if ( !cache.has( key ) )
{
cache.set( key, fn( ...args ) );
}
return cache.get( key )!;
};
}
// End. :: - - - -