1 var MapCache = require('./_MapCache');
3 /** Used as the `TypeError` message for "Functions" methods. */
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 [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
16 * method interface of `delete`, `get`, `has`, and `set`.
21 * @param {Function} func The function to have its output memoized.
22 * @param {Function} [resolver] The function to resolve the cache key.
23 * @returns {Function} Returns the new memoizing function.
26 * var object = { 'a': 1, 'b': 2 };
27 * var other = { 'c': 3, 'd': 4 };
29 * var values = _.memoize(_.values);
40 * // Modify the result cache.
41 * values.cache.set(object, ['a', 'b']);
45 * // Replace `_.memoize.Cache`.
46 * _.memoize.Cache = WeakMap;
48 function memoize(func, resolver) {
49 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
50 throw new TypeError(FUNC_ERROR_TEXT);
52 var memoized = function() {
54 key = resolver ? resolver.apply(this, args) : args[0],
55 cache = memoized.cache;
58 return cache.get(key);
60 var result = func.apply(this, args);
61 memoized.cache = cache.set(key, result);
64 memoized.cache = new memoize.Cache;
68 // Assign cache to `_.memoize`.
69 memoize.Cache = MapCache;
71 module.exports = memoize;