Skip to content

memoize

js
_.memoize(func, [resolver])

创建一个记忆 func 结果的函数。如果提供了 resolver,则根据提供给 memoized 函数的参数确定用于存储结果的缓存键。默认情况下,提供给 memoized 函数的第一个参数用作 map 缓存键。func 使用记忆函数的 this 绑定调用。

¥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. By default, the first argument provided to the memoized function is used as the map cache key. The func is invoked with the this binding of the memoized function.

注意:缓存在 memoized 函数上显示为 cache 属性。可以通过将 _.memoize.Cache 构造函数替换为其实例实现 cleardeletegethassetMap 方法接口的构造函数来定制其创建。

¥Note: The cache is exposed as the cache property on the memoized function. Its creation may be customized by replacing the _.memoize.Cache constructor with one whose instances implement the Map method interface of clear, delete, get, has, and set.

新增于

¥Since

0.1.0

参数

¥Arguments

  1. func (函数):将其输出记忆化的函数。

    ¥func (Function): The function to have its output memoized.

  2. [resolver] (函数):解析缓存键的函数。

    ¥[resolver] (Function): The function to resolve the cache key.

返回

¥Returns

(函数):返回新的记忆函数。

¥(Function): Returns the new memoized function.

示例

¥Example

js
var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };

var values = _.memoize(_.values);
values(object);
// => [1, 2]

values(other);
// => [3, 4]

object.a = 2;
values(object);
// => [1, 2]

// Modify the result cache.
values.cache.set(object, ['a', 'b']);
values(object);
// => ['a', 'b']

// Replace `_.memoize.Cache`.
_.memoize.Cache = WeakMap;

Lodash v4.17 中文网 - 粤ICP备13048890号