Initial commit
[yaffs-website] / node_modules / grunt-contrib-watch / node_modules / lodash / function / 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 coerced to a string and used as the
11  * cache key. The `func` is invoked with the `this` binding of the memoized
12  * function.
13  *
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`.
18  *
19  * @static
20  * @memberOf _
21  * @category Function
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.
25  * @example
26  *
27  * var upperCase = _.memoize(function(string) {
28  *   return string.toUpperCase();
29  * });
30  *
31  * upperCase('fred');
32  * // => 'FRED'
33  *
34  * // modifying the result cache
35  * upperCase.cache.set('fred', 'BARNEY');
36  * upperCase('fred');
37  * // => 'BARNEY'
38  *
39  * // replacing `_.memoize.Cache`
40  * var object = { 'user': 'fred' };
41  * var other = { 'user': 'barney' };
42  * var identity = _.memoize(_.identity);
43  *
44  * identity(object);
45  * // => { 'user': 'fred' }
46  * identity(other);
47  * // => { 'user': 'fred' }
48  *
49  * _.memoize.Cache = WeakMap;
50  * var identity = _.memoize(_.identity);
51  *
52  * identity(object);
53  * // => { 'user': 'fred' }
54  * identity(other);
55  * // => { 'user': 'barney' }
56  */
57 function memoize(func, resolver) {
58   if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
59     throw new TypeError(FUNC_ERROR_TEXT);
60   }
61   var memoized = function() {
62     var args = arguments,
63         key = resolver ? resolver.apply(this, args) : args[0],
64         cache = memoized.cache;
65
66     if (cache.has(key)) {
67       return cache.get(key);
68     }
69     var result = func.apply(this, args);
70     memoized.cache = cache.set(key, result);
71     return result;
72   };
73   memoized.cache = new memoize.Cache;
74   return memoized;
75 }
76
77 // Assign cache to `_.memoize`.
78 memoize.Cache = MapCache;
79
80 module.exports = memoize;