Skip to content

Commit

Permalink
Fix usage of hash function in _.memoize.
Browse files Browse the repository at this point in the history
The function `_.memoize` has a bug where the first argument to the
function is used as the key when retrieving a result from the cache,
ignoring the hash function.

The fix is always to use the computed `address` as the key to the cache.

Confirmed the regression and fix with the updated unit test.
  • Loading branch information
bdusell authored and michaelficarra committed Jul 15, 2014
1 parent cf85c77 commit 9a74517
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 12 additions & 0 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,18 @@
});
hashed('yep');
deepEqual(hashed.cache, {'YEP': 'yep'}, 'takes a hasher');

// Test that the hash function can be used to swizzle the key.
var objCacher = _.memoize(function(value, key) {
return {key: key, value: value};
}, function(value, key) {
return key;
});
var myObj = objCacher('a', 'alpha');
var myObjAlias = objCacher('b', 'alpha');
notStrictEqual(myObj, undefined, 'object is created if second argument used as key');
strictEqual(myObj, myObjAlias, 'object is cached if second argument used as key');
strictEqual(myObj.value, 'a', 'object is not modified if second argument used as key');
});

asyncTest('delay', 2, function() {
Expand Down
2 changes: 1 addition & 1 deletion underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@
var cache = memoize.cache;
var address = hasher ? hasher.apply(this, arguments) : key;
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[key];
return cache[address];
};
memoize.cache = {};
return memoize;
Expand Down

0 comments on commit 9a74517

Please sign in to comment.