UNPKG

2.33 kBJavaScriptView Raw
1/**
2 * Lo-Dash 2.2.0 (Custom Build) <http://lodash.com/>
3 * Build: `lodash modularize modern exports="npm" -o ./npm`
4 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
5 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
6 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
7 * Available under MIT license <http://lodash.com/license>
8 */
9var isFunction = require('lodash.isfunction'),
10 keyPrefix = require('lodash._keyprefix');
11
12/** Used for native method references */
13var objectProto = Object.prototype;
14
15/** Native method shortcuts */
16var hasOwnProperty = objectProto.hasOwnProperty;
17
18/**
19 * Creates a function that memoizes the result of `func`. If `resolver` is
20 * provided it will be used to determine the cache key for storing the result
21 * based on the arguments provided to the memoized function. By default, the
22 * first argument provided to the memoized function is used as the cache key.
23 * The `func` is executed with the `this` binding of the memoized function.
24 * The result cache is exposed as the `cache` property on the memoized function.
25 *
26 * @static
27 * @memberOf _
28 * @category Functions
29 * @param {Function} func The function to have its output memoized.
30 * @param {Function} [resolver] A function used to resolve the cache key.
31 * @returns {Function} Returns the new memoizing function.
32 * @example
33 *
34 * var fibonacci = _.memoize(function(n) {
35 * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
36 * });
37 *
38 * var data = {
39 * 'moe': { 'name': 'moe', 'age': 40 },
40 * 'curly': { 'name': 'curly', 'age': 60 }
41 * };
42 *
43 * // modifying the result cache
44 * var stooge = _.memoize(function(name) { return data[name]; }, _.identity);
45 * stooge('curly');
46 * // => { 'name': 'curly', 'age': 60 }
47 *
48 * stooge.cache.curly.name = 'jerome';
49 * stooge('curly');
50 * // => { 'name': 'jerome', 'age': 60 }
51 */
52function memoize(func, resolver) {
53 if (!isFunction(func)) {
54 throw new TypeError;
55 }
56 var memoized = function() {
57 var cache = memoized.cache,
58 key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
59
60 return hasOwnProperty.call(cache, key)
61 ? cache[key]
62 : (cache[key] = func.apply(this, arguments));
63 }
64 memoized.cache = {};
65 return memoized;
66}
67
68module.exports = memoize;