moize icon indicating copy to clipboard operation
moize copied to clipboard

Class methods?

Open Emsu opened this issue 2 years ago • 4 comments

Is there a way to use moize with class methods?

Emsu avatar May 12 '23 06:05 Emsu

I was looking into how decorators work. Would it make sense to add a class method decorator? @planttheidea

function MoizeCache(target, key, descriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = moize(originalMethod.bind(target));
  return descriptor;
}

Usage could be like this?

class MyClass {
  @MoizeCache
  myMethod(arg1, arg2) {
    console.log('Method called with:', arg1, arg2);
    // Your method implementation
    return arg1 + arg2;
  }
}

Emsu avatar May 13 '23 00:05 Emsu

Sorry for the late reply, its been a busy few weeks.

Honestly, my first inclination is no, for a few reasons:

  • The decorator proposal has been languishing for years and been through multiple revisions. It is at Stage 3, but was last presented in March 2022 ... not sure when (if ever) it will be adopted as part of the standard.
  • The example you provide is just one possible decorator use; another possible usage would be as a class decorator. Supporting only one has the potential for misuse or confusion for consumers, and supporting both creates API questions that would require some thought.
  • Support for the full gamut of options that moize supports is possible with a factory approach, but the shorthand is a common usage as well, and finding a small footprint solution for that full support would be a challenge.

This is the first request I've had for decorators, but I think for now it makes sense to put it in the same bucket as React hooks and leave it to consumers to build their own abstraction. The example you provided is very straightforward to write, and avoids the complexities above. If you want, you can submit a PR to add documentation for this like the useMoize hook, and I can incorporate it as another simple userland abstraction.

That said, if decorators ever make it into the official spec, I'll reconsider this proposal.

planttheidea avatar May 24 '23 02:05 planttheidea