UNPKG

2.22 kBJavaScriptView Raw
1var MapCache = require('./_MapCache');
2
3/** Error message constants. */
4var FUNC_ERROR_TEXT = 'Expected a function';
5
6/**
7 * Creates a function that memoizes the result of `func`. If `resolver` is
8 * provided, it determines the cache key for storing the result based on the
9 * arguments provided to the memoized function. By default, the first argument
10 * provided to the memoized function is used as the map cache key. The `func`
11 * is invoked with the `this` binding of the memoized function.
12 *
13 * **Note:** The cache is exposed as the `cache` property on the memoized
14 * function. Its creation may be customized by replacing the `_.memoize.Cache`
15 * constructor with one whose instances implement the
16 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
17 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
18 *
19 * @static
20 * @memberOf _
21 * @since 0.1.0
22 * @category Function
23 * @param {Function} func The function to have its output memoized.
24 * @param {Function} [resolver] The function to resolve the cache key.
25 * @returns {Function} Returns the new memoized function.
26 * @example
27 *
28 * var object = { 'a': 1, 'b': 2 };
29 * var other = { 'c': 3, 'd': 4 };
30 *
31 * var values = _.memoize(_.values);
32 * values(object);
33 * // => [1, 2]
34 *
35 * values(other);
36 * // => [3, 4]
37 *
38 * object.a = 2;
39 * values(object);
40 * // => [1, 2]
41 *
42 * // Modify the result cache.
43 * values.cache.set(object, ['a', 'b']);
44 * values(object);
45 * // => ['a', 'b']
46 *
47 * // Replace `_.memoize.Cache`.
48 * _.memoize.Cache = WeakMap;
49 */
50function memoize(func, resolver) {
51 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
52 throw new TypeError(FUNC_ERROR_TEXT);
53 }
54 var memoized = function() {
55 var args = arguments,
56 key = resolver ? resolver.apply(this, args) : args[0],
57 cache = memoized.cache;
58
59 if (cache.has(key)) {
60 return cache.get(key);
61 }
62 var result = func.apply(this, args);
63 memoized.cache = cache.set(key, result) || cache;
64 return result;
65 };
66 memoized.cache = new (memoize.Cache || MapCache);
67 return memoized;
68}
69
70// Expose `MapCache`.
71memoize.Cache = MapCache;
72
73module.exports = memoize;