medikoo / memoizee

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

Easiest way to ignore an argument for memoization #44

Closed bojand closed 9 years ago

bojand commented 9 years ago

Let's say I have an async function:

function verifyToken(token, fn) {
   ...
}`;

This can easily be momoized with something like:

var memoized = memoize(verifyToken, {async: true, length: 1});

What if I have a function:

function verifyToken(req, token, fn) {
  ...
}`;

where req is Express request object. I would not like the req value to be considered for hashing at all. We should still memoize results of verifyToken based on token value only. What's the easiest approach to accomplish this? Resolvers? Something like:

var memoized = memoize(verifyToken, {async: true, length: 2, resolvers: [Boolean, String]});

? This way req (which will always be there) will always just be coersed to true and token will be coersed to String as normal. Just want to check if this the best approach? Thanks!

medikoo commented 9 years ago

You can ignore arguments, but only trailing ones, not leading ones.

So I believe it would work as expected if you do:

function verifyToken(token, req, fn) {
  ...
};
var memoized = memoize(verifyToken, { async: true, length 1 });

I'm closing it, as it's neither bug report nor feature request, still let's continue discussion

bojand commented 9 years ago

Thanks for the reply. Yea it's just a usage question, not a bug. Sorry i should have made it clearer... I don't have a choice of argument ordering due to contextual factors. so the argument order in function signature has to be (req, token, fn). I imagine I could do something hacky-ish perhaps with lexical closur-ing and/or partial-ing + memo, but wanted to know if there was a simpler approach?

medikoo commented 9 years ago

The other approach would be to solve it via decorator pattern:

var memoized = memoize(function (token, req, fn) {
 ...
}, { async: true, length 1 });

function verifyToken(req, token, fn) {
  return memoized(token, req, fn);
};