medikoo / memoizee

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

What is the best way to delete cache for a group of arguments? #16

Closed mryangyu closed 10 years ago

mryangyu commented 10 years ago

lets say I remembered by 2 arguments: a, b, and then I want to clear the cache for all a = 1 regardless what b is.

Thanks for the help.

medikoo commented 10 years ago

@mryangyu I think the only way to do it, would be by writing custom normalizer. What is the use case for that?

medikoo commented 10 years ago

I'm going to close this, but let's keep discussion open

mryangyu commented 10 years ago

I'm using it to cache web api requests for a given city and normalized query string. When users add records in a city I need to expire all the cache of a given city.

medikoo commented 10 years ago

@mryangyu then best thing you can do, is to write custom normalizer. e.g.:

var baseNormalizer = require('memoizee/normalizers/get-primitive-fixed')(2)
var citiesMap = Object.create(null);
var normalizer = function (args) {
    var city = args[0];
    if (!citiesMap[city]) citiesMap[city] = Object.create(null);
    citiesMap[city][args[1]] = true;
    return baseNormalizer(args);
};

var mfn = memoize(fn, { normalizer: normalizer });

mfn.clearByCity = function (city) {
    if (!citiesMap[city]) return;
    for (query in citiesMap[city]) mfn.delete(city, query);
    delete citiesMap[city];
};

Then use mfn.clearByCity(city) to clear all memoized calls for given city. I assumed that both city and query are strings in your case.

Let me know if something is not clear