Decorator for caching the results of your method calls using lodash.memoize
npm install memo-decorator
This decorator applies memoization to a method of a class.
Apply the decorator to a method of a class. The cache is local for the method but shared among all instances of the class. Strongly recommend you to use this decorator only on pure methods.
Installation:
``shell`
npm i memo-decorator --save
`ts`
export interface Config {
resolver?: Resolver;
cache?: MapLike;
}
- Resolver is a function, which returns the key to be used for given set of arguments. By default, the resolver will use the first argument of the method as the key.MapLike
- is a cache instance. By default, the library would use Map.
Example:
`typescript
import memo from 'memo-decorator';
class Qux {
@memo({
resolver: (...args: any[]) => args[1],
cache: new WeakMap()
})
foo(a: number, b: number) {
return a * b;
}
}
`
`typescript
import memo from 'memo-decorator';
class Qux {
@memo()
foo(a: number) {
console.log('foo: called');
return 42;
}
@memo({
resolver: _ => 1
})
bar(a: number) {
console.log('bar: called');
return 42;
}
}
const a = new Qux();
// Create a new cache entry and associate 1 with the result 42.foo
a.foo(1);
// Do not invoke the original method because there's already a cache1
// entry for the key associated with the result of the method.foo
a.foo(1);
// Invoke the original because the cache doesn't contain an entry2
// for the key .
a.foo(2);
// Invoke bar and return the result 42 gotten from the original bar implementation.bar
a.bar(1);
// Does not invoke the original implementation because of the specified resolvermemo
// which is passed to . For any arguments of the function, the resolver will return1
// result which will be used as the key.
a.bar(2);
const b = new Qux();
// Does not invoke the method foo because there's already an entry1
// in the cache which associates the key to the result 42 from thefoo
// invocation of the method by the instance a.
b.foo(1);
// Outputs:
// foo: called
// foo: called
// bar: called
``
MIT