typescript-memoize icon indicating copy to clipboard operation
typescript-memoize copied to clipboard

Cache tags for generic classes?

Open markericson opened this issue 2 years ago • 1 comments

First, kudos! I love this @memoize decorator implementation! My first exploration into implementing decorators was a form of memoization, but I did take it as far as you did.

However today I came across a use case for using @memoize that I'm not sure how to accomplish, and I'm wondering if it is even possible.

Scenario I

I have a generic class and need separate cached memoization for a method for each class<T> that I use.

I was very pleasantly surprised this works as hoped!

Scenario II

I would like a distinct cache tag for each class<T> I might use so I can clear the cache for a specific cached resource.

This does not seem possible since @memoize() takes literal cache keys and that doesn't help with my generic class.

So maybe, if feasible, since @memoize() can already differentiate between MyClass<A> and MyClass<B> it can automatically generate a distinct cache key for classes (including generic classes) to clear the cache separately?

Example:

import {memoize, clear} from 'typescript-memoize'

class MyClass<T extend A> {
  // memoize the findAll() method, 
  // would like a key for MyClass<T> but string literal won't work
  @memoize(tags: ['findAll'] ) 
  findAll() : T[] { /*implementation*/ }
}

class A {}
class B : extends A {}

b = new MyClass<B>()
allB = b.findAll()

// some time later...

// clear 'findAll' resources for a specific generic class instance
// but what key to use for the generic class?
clear(['findAll', 'MyClass<B>'] 

markericson avatar Oct 04 '23 17:10 markericson

Since the class instance (object) appears to be the hash key for the value; might it be possible to support clear with that object? Not exactly what i want, I would prefer to clear for all instances of the same Class<T>, but that may not be feasible.

markericson avatar Oct 04 '23 17:10 markericson