Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_.memoize only cache's first argument

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?

like image 749
chopper draw lion4 Avatar asked Feb 05 '26 21:02

chopper draw lion4


1 Answers

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>
like image 80
Amadan Avatar answered Feb 07 '26 11:02

Amadan