-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorator.ts
More file actions
48 lines (43 loc) · 1.3 KB
/
decorator.ts
File metadata and controls
48 lines (43 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* @file `Memoize` — class-method decorator that wraps the decorated method via
* `memoize`. Preserves `this`-context by installing the wrapper on the
* property descriptor. Defaults the cache `name` option to the property key
* for nicer debug output.
*/
import { memoize } from './memoize'
import type { MemoizeOptions } from './types'
/**
* Create a memoized version of a method. Preserves 'this' context for class
* methods.
*
* @example
* import { Memoize } from '@socketsecurity/lib/memo/decorator'
*
* class Calculator {
* @Memoize()
* fibonacci(n: number): number {
* if (n <= 1) return n
* return this.fibonacci(n - 1) + this.fibonacci(n - 2)
* }
* }
*
* @param target - Object containing the method.
* @param propertyKey - Method name.
* @param descriptor - Property descriptor.
*
* @returns Modified descriptor with memoized method
*/
export function Memoize(options: MemoizeOptions<unknown[]> = {}) {
return (
_target: unknown,
propertyKey: string,
descriptor: PropertyDescriptor,
): PropertyDescriptor => {
const originalMethod = descriptor.value as (...args: unknown[]) => unknown
descriptor.value = memoize(originalMethod, {
...options,
name: options.name || propertyKey,
})
return descriptor
}
}