medikoo / memoizee

Complete memoize/cache solution for JavaScript
ISC License
1.73k stars 61 forks source link

How to properly memoizee with array/hash params ? #2

Closed puzrin closed 11 years ago

puzrin commented 11 years ago

First af all, that does not affect our code, because we use "premitive" mode (params consist of unique mongoose ids). But I'd like to understand, how to properly handle arrays/hash params in other case.

https://gist.github.com/3974038

This example does not memoize. What is wrong with code?

PS. Thanks for module.

medikoo commented 11 years ago

Sorry for late response (again I didn't get notification from github).

In regular mode (not primitive), values are taken as they are in JavaScript. In your example you create three different arrays (it doesn't matter that they have same values), therefore memoize sees them as different objects.

If you pass same array, memoize will accept it as same value, e.g. following would cache as expected:

var arr = [1,2,3];
cached(arr, function (err, res) {
  cached(arr, function (err, res) {
    cached(arr, function (err, res) {
      console.log('done');
    });
  });
});

In primitive mode, internal id's are get by conversion to string, so arrays with same values are treated as equal

var arr1 = [1, 2, 3];
var arr2 = [1, 2, 3];
var arr3 = [1, 2, 3];

String(arr1) === String(arr2); // true
String(arr2) === String(arr3); // true
puzrin commented 11 years ago

Thanks. I expected something like this. Probably, this should be specially noted in readme. That primitive mode is the only way to work with array/hash params.

puzrin commented 11 years ago

Did pull request with note in coerce section.