medikoo / memoizee

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

Function with object as parameters #46

Closed diegosanchez closed 8 years ago

diegosanchez commented 8 years ago

Memoize works with strings and numbers but not with more complex parameters like objects like {x:1, y: 1}

Here the pice of code:

var m = require("memoizee");

// not a big deal!
var f = function(a,b)  { console.log(arguments);}

var mf = m(f);

// I had a miss
mf(1,2)
{ '0': 1, '1': 2 }

// I had a hit and that's fine!
mf(1,2)

// Now

// In both successive calls I always got a miss 
mf(1,{ x:1, y:1})
{ '0': 1, '1': { x: 1, y: 1 } }

mf(1,{ x:1, y:1})
{ '0': 1, '1': { x: 1, y: 1 } }

I will be nice to have deep comparison, won't it? May be there is a performance consideration to have.

medikoo commented 8 years ago

It's expected, as in both cases you pass different objects, therefore different arguments. It will pass if it would be done as following:

var obj = { x: 1, y: 1 };
mf(1, obj); // miss
mf(1, obj); // hit

You can however provide your own normalizer, so even if they're different object, they're recognized as same ones:

var mf = m(f, { normalizer: function (args): {
return String(args[0]) + JSON.stringify(args[1]);
} });

mf(1,{ x:1, y:1}); // miss
mf(1,{ x:1, y:1}); // hit