memoize

function

Creates 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

NameTypeDescription
funcTThe function to have its output memoized
resolver?(...args: Parameters<T>) => anyThe 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) // Cached

With 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) // Cached

Available since version 1.0.0