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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With