From 9bd0c01702ea8619f030f3490f86b45ab9abc94d Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Fri, 10 May 2013 23:20:10 -0700 Subject: [PATCH] Expose memoized function's `cache`. [closes #265] Former-commit-id: fc44676386854ec9d5fd7a4fac8583508d63949f --- build/pre-compile.js | 1 + lodash.js | 11 +++++++---- test/test.js | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) 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() {