diff --git a/build/pre-compile.js b/build/pre-compile.js index 107b281b3..ffe53a78e 100644 --- a/build/pre-compile.js +++ b/build/pre-compile.js @@ -93,6 +93,7 @@ 'bind', 'bindAll', 'bindKey', + 'cache', 'clearTimeout', 'clone', 'cloneDeep', diff --git a/lodash.js b/lodash.js index 42973fce7..ad117f5c5 100644 --- a/lodash.js +++ b/lodash.js @@ -4615,13 +4615,16 @@ * }); */ function memoize(func, resolver) { - var cache = {}; - return function() { - var key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]); + function memoized() { + var cache = memoized.cache, + key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]); + return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); - }; + } + memoized.cache = {}; + return memoized; } /** diff --git a/test/test.js b/test/test.js index 7155a425d..3f4518106 100644 --- a/test/test.js +++ b/test/test.js @@ -1900,6 +1900,22 @@ /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.memoize'); + + (function() { + test('should expose a `cache` object on the `memoized` function', function() { + var memoized = _.memoize(_.identity); + memoized('x'); + + var cache = memoized.cache, + key = _.keys(cache)[0]; + + equal(cache[key], 'x'); + }); + }()); + + /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.merge'); (function() {