Skip to content

Commit

Permalink
Expose the memoize cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
braddunbar committed May 6, 2014
1 parent 9e4d431 commit bdb60c8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
10 changes: 10 additions & 0 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,16 @@
var fastO = _.memoize(o);
equal(o('toString'), 'toString', 'checks hasOwnProperty');
equal(fastO('toString'), 'toString', 'checks hasOwnProperty');

// Expose the cache.
var i = 0;
var f = _.memoize(function() {
return ++i;
});
equal(f('x'), 1);
equal(f('x'), 1);
f.cache = {};
equal(f('x'), 2);
});

asyncTest('delay', 2, function() {
Expand Down
11 changes: 7 additions & 4 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -641,12 +641,15 @@

// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
if (!hasher) hasher = _.identity;
var memoize = function() {
var cache = memoize.cache;
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
if (_.has(cache, key)) return cache[key];
return cache[key] = func.apply(this, arguments);
};
memoize.cache = {};
return memoize;
};

// Delays a function for the given number of milliseconds, and then calls
Expand Down

0 comments on commit bdb60c8

Please sign in to comment.