dd164edda5d93d0c7dfcef713b56a013ddf23884
[yaffs-website] / node_modules / uncss / node_modules / lodash / memoize.js
1 var MapCache = require('./internal/MapCache');
2
3 /** Used as the `TypeError` message for "Functions" methods. */
4 var 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 [`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`.
17  *
18  * @static
19  * @memberOf _
20  * @category Function
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.
24  * @example
25  *
26  * var object = { 'a': 1, 'b': 2 };
27  * var other = { 'c': 3, 'd': 4 };
28  *
29  * var values = _.memoize(_.values);
30  * values(object);
31  * // => [1, 2]
32  *
33  * values(other);
34  * // => [3, 4]
35  *
36  * object.a = 2;
37  * values(object);
38  * // => [1, 2]
39  *
40  * // modifying the result cache
41  * values.cache.set(object, ['a', 'b']);
42  * values(object);
43  * // => ['a', 'b']
44  *
45  * // replacing `_.memoize.Cache`
46  * _.memoize.Cache = WeakMap;
47  */
48 function memoize(func, resolver) {
49   if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
50     throw new TypeError(FUNC_ERROR_TEXT);
51   }
52   var memoized = function() {
53     var args = arguments,
54         key = resolver ? resolver.apply(this, args) : args[0],
55         cache = memoized.cache;
56
57     if (cache.has(key)) {
58       return cache.get(key);
59     }
60     var result = func.apply(this, args);
61     memoized.cache = cache.set(key, result);
62     return result;
63   };
64   memoized.cache = new memoize.Cache;
65   return memoized;
66 }
67
68 // Assign cache to `_.memoize`.
69 memoize.Cache = MapCache;
70
71 module.exports = memoize;