Skip to content

Function: memoize()

ts
function memoize<T>(fn): T;

Creates a memoized version of a function that caches results for identical arguments. 创建函数的记忆化版本,为相同参数缓存结果。

The memoized function will cache the result of the first call with specific arguments and return the cached result on subsequent calls with the same arguments. 记忆化函数将缓存第一次调用特定参数的结果, 并在后续使用相同参数调用时返回缓存的结果。

Type Parameters

Type ParameterDescription
T extends MemoizeFnThe type of the function to memoize / 要记忆化的函数类型

Parameters

ParameterTypeDescription
fnTThe function to be memoized / 要记忆化的函数

Returns

T

The memoized function / 记忆化的函数

Example

typescript
function fibonacci(n) {
  if (n <= 1) return n
  return fibonacci(n - 1) + fibonacci(n - 2)
}
const memoizedFib = memoize(fibonacci)
memoizedFib(10) // => 55
memoizedFib(10) // => 55 (cached)

const op = (a, b) => `${a}-${b * 2}`
const memoized = memoize(op)
memoized('test', 5) // => "test-10"
memoized('test', 5) // => "test-10" (cached)

Since

1.0.0

Released under the MIT License.