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 badges2 Answers
Reset to default 9Deliberate. 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
评论列表(0条)