memoize
functionCreates a function that memoizes the result of func. If resolver is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function.
Signature
memoize<T extends (...args: any[]) => any>(func: T, resolver?: (...args: Parameters<T>) => any): T & { cache: Map<any, any> }Parameters
| Name | Type | Description |
|---|---|---|
func | T | The function to have its output memoized |
resolver? | (...args: Parameters<T>) => any | The function to resolve the cache key |
Returns
T & { cache: Map<any, any> } - Returns the new memoized function
Examples
Fibonacci
import { memoize } from 'dashlite'
const fibonacci = memoize((n: number): number => {
if (n <= 1) return n
return fibonacci(n - 1) + fibonacci(n - 2)
})
fibonacci(10) // Computed
fibonacci(10) // CachedWith Resolver
import { memoize } from 'dashlite'
const sum = memoize(
(a: number, b: number) => a + b,
(a, b) => `${a}-${b}`
)
sum(1, 2) // Computed
sum(1, 2) // CachedAvailable since version 1.0.0