-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorator.ts
More file actions
47 lines (42 loc) · 1.28 KB
/
decorator.ts
File metadata and controls
47 lines (42 loc) · 1.28 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
/**
* @fileoverview `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.
*
* @param target - Object containing the method
* @param propertyKey - Method name
* @param descriptor - Property descriptor
* @returns Modified descriptor with memoized method
*
* @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)
* }
* }
*/
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
}
}