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

I realized today that the _memoize function only caches results for the first argument provided.functio

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745345144a4623508.html

相关推荐

  • javascript - _.memoize only cache&#39;s first argument - Stack Overflow

    I realized today that the _memoize function only caches results for the first argument provided.functio

    1小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信