1 var MapCache = require('./_MapCache');
3 /** Error message constants. */
4 var FUNC_ERROR_TEXT = 'Expected a function';
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.
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`.
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.
28 * var object = { 'a': 1, 'b': 2 };
29 * var other = { 'c': 3, 'd': 4 };
31 * var values = _.memoize(_.values);
42 * // Modify the result cache.
43 * values.cache.set(object, ['a', 'b']);
47 * // Replace `_.memoize.Cache`.
48 * _.memoize.Cache = WeakMap;
50 function memoize(func, resolver) {
51 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
52 throw new TypeError(FUNC_ERROR_TEXT);
54 var memoized = function() {
56 key = resolver ? resolver.apply(this, args) : args[0],
57 cache = memoized.cache;
60 return cache.get(key);
62 var result = func.apply(this, args);
63 memoized.cache = cache.set(key, result) || cache;
66 memoized.cache = new (memoize.Cache || MapCache);
71 memoize.Cache = MapCache;
73 module.exports = memoize;