Reputation: 13487
I realized today that the _memoize function only caches results for the first argument provided.
function add(a, b) {
return a + b;
}
var sum = _.memoize(add);
console.log(sum(1,2));
>>> 3
console.log(sum(1,5));
>>> 3
Is this a bug or deliberate?
Upvotes: 2
Views: 1972
Reputation: 1
const g = _.memoize(([a, b]) => a + b)
console.log(g([1, 2]))
console.log(g([1, 3]))
console.log(g([1, 4]))
pass all as the first argument
Upvotes: 0
Reputation: 198314
Deliberate. Relevant docs:
The default hashFunction just uses the first argument to the memoized function as the key.
But good news is you can change this behaviour by introducing your own hash function.
function myInefficientHashFunction() {
// not really an efficient hash function
return JSON.stringify(arguments);
}
function add(a, b) {
return a + b;
}
var sum = _.memoize(add, myInefficientHashFunction);
document.getElementById('one_two').textContent = sum(1, 2)
document.getElementById('one_three').textContent = sum(1, 3)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<div>1 + 2 = <span id="one_two"/></div>
<div>1 + 3 = <span id="one_three"/></div>
Upvotes: 9