_.memoize 仅缓存的第一个参数

_.memoize only cache's first argument

我今天意识到 _memoize 函数只缓存提供的第一个参数的结果。

function add(a, b) {
  return a + b;
}
var sum = _.memoize(add);
console.log(sum(1,2));
>>> 3
console.log(sum(1,5));
>>> 3

这是错误还是故意的?

故意的。 Relevant docs:

The default hashFunction just uses the first argument to the memoized function as the key.

但好消息是您可以通过引入自己的哈希函数来改变这种行为。

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>

const g = _.memoize(([a, b]) => a + b)
console.log(g([1, 2]))
console.log(g([1, 3]))
console.log(g([1, 4]))

全部作为第一个参数传递