Memo
Memo
is a class callable with memoization logic which it stores computation results in cache, and retrieve that same information from the cache the next time it’s needed instead of computing it again.
Memoization is a powerful trick that can help speed up our code, especially when dealing with repetitive and heavy computing functions.
Syntax
Memo
accepts these properties:
-
computeValue
: A method that takes an argument of typeA
and returns a value ofT
type. This is the core function that will be memoized. interceptor
: AMemoInterceptor
that allows you to intercept the memoization function calls and modify the memoization process. Reactter providers some interceptors:-
MemoSafeAsyncInterceptor
: prevents caching if theFuture
calculation function throws an error during execution. -
MemoTemporaryCacheInterceptor
: removes memoized values from the cache after a specified duration. -
MemoWrapperInterceptor
: Wraps a memoized function, enabling the definition of callbacks for initialization, successful completion, error handling, and finishing. -
MemoMultiInterceptor
: allows multiple memoization interceptors to be used together.
-
Methods
Memo
provides the following methods that will help you manipulate the cache as you wish:
-
get
: Returns the cached value by argument passed.- Syntax:
-
remove
: Removes the cached value by argument passed.- Syntax:
-
clear
: Removes all cached data.- Syntax:
Example
Here’s an example of factorial using Memo
:
In the above example, the factorialMemo
function is called with different numbers, and the results are stored in the cache.
When the same number is passed to the factorialMemo
function again, the result is retrieved from the cache instead of recalculating it.