1 var MapCache = require('../internal/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 coerced to a string and used as the
11 * cache key. The `func` is invoked with the `this` binding of the memoized
14 * **Note:** The cache is exposed as the `cache` property on the memoized
15 * function. Its creation may be customized by replacing the `_.memoize.Cache`
16 * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
17 * method interface of `get`, `has`, and `set`.
22 * @param {Function} func The function to have its output memoized.
23 * @param {Function} [resolver] The function to resolve the cache key.
24 * @returns {Function} Returns the new memoizing function.
27 * var upperCase = _.memoize(function(string) {
28 * return string.toUpperCase();
34 * // modifying the result cache
35 * upperCase.cache.set('fred', 'BARNEY');
39 * // replacing `_.memoize.Cache`
40 * var object = { 'user': 'fred' };
41 * var other = { 'user': 'barney' };
42 * var identity = _.memoize(_.identity);
45 * // => { 'user': 'fred' }
47 * // => { 'user': 'fred' }
49 * _.memoize.Cache = WeakMap;
50 * var identity = _.memoize(_.identity);
53 * // => { 'user': 'fred' }
55 * // => { 'user': 'barney' }
57 function memoize(func, resolver) {
58 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
59 throw new TypeError(FUNC_ERROR_TEXT);
61 var memoized = function() {
63 key = resolver ? resolver.apply(this, args) : args[0],
64 cache = memoized.cache;
67 return cache.get(key);
69 var result = func.apply(this, args);
70 memoized.cache = cache.set(key, result);
73 memoized.cache = new memoize.Cache;
77 // Assign cache to `_.memoize`.
78 memoize.Cache = MapCache;
80 module.exports = memoize;