Skip to content

Commit 0b09cb0

Browse files
committed
Simplify decorator code
1 parent 0152609 commit 0b09cb0

File tree

1 file changed

+15
-24
lines changed

1 file changed

+15
-24
lines changed

src/decorator.ts

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,10 @@ import { memoize as memoizeFn } from './index.js';
1313
* @param options.cacheFromContext - Function returning a custom cache instance that has access to the original function's context `this`.
1414
* @returns Memoized class method or getter.
1515
*/
16-
export function memoize<Fn extends AnyFunction, CacheID>(
17-
options: MemoizeOptions<Fn, CacheID> = {}
18-
) {
19-
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): void {
20-
if (typeof descriptor?.value === 'function') {
21-
// Method
22-
descriptor.value = createMemoizedFn(descriptor.value, options);
23-
} else if (typeof descriptor?.get === 'function') {
24-
// Accessor
25-
descriptor.get = createMemoizedFn(descriptor.get, options);
26-
} else {
27-
throw new Error('Memoize decorator can only be used on a method or a getter.');
28-
}
29-
};
30-
}
31-
32-
function createMemoizedFn<Fn extends AnyFunction, CacheID>(
33-
fn: Fn,
34-
{
35-
cache = () => new Map<CacheID, CacheContent<Fn>>(),
36-
...options
37-
}: MemoizeOptions<Fn, CacheID> = {}
38-
) {
16+
export function memoize<Fn extends AnyFunction, CacheID>({
17+
cache = () => new Map<CacheID, CacheContent<Fn>>(),
18+
...options
19+
}: MemoizeOptions<Fn, CacheID> = {}) {
3920
const cacheMap = new WeakMap<object, Cache<CacheID, CacheContent<Fn>>>();
4021

4122
// In this case `this` is going to be the class instance
@@ -47,5 +28,15 @@ function createMemoizedFn<Fn extends AnyFunction, CacheID>(
4728
return cacheMap.get(this)!;
4829
}
4930

50-
return memoizeFn(fn, { cacheFromContext, ...options });
31+
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): void {
32+
if (typeof descriptor?.value === 'function') {
33+
// Method
34+
descriptor.value = memoizeFn(descriptor.value as Fn, { cacheFromContext, ...options });
35+
} else if (typeof descriptor?.get === 'function') {
36+
// Accessor
37+
descriptor.get = memoizeFn(descriptor.get as Fn, { cacheFromContext, ...options });
38+
} else {
39+
throw new Error('Memoize decorator can only be used on a method or a getter.');
40+
}
41+
};
5142
}

0 commit comments

Comments
 (0)