最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - _.memoize only cache's first argument - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Jan 27, 2015 at 2:10 chopper draw lion4chopper draw lion4 13.6k17 gold badges62 silver badges103 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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./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]))

pass all as the first argument

发布评论

评论列表(0)

  1. 暂无评论