-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmemo.ts
More file actions
33 lines (25 loc) · 809 Bytes
/
memo.ts
File metadata and controls
33 lines (25 loc) · 809 Bytes
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
// A decorator that memoizes a function's arguments and return value.
type Primitive = string | number | bigint | boolean | symbol | null | undefined
export function memo<This, P extends Primitive, R>(
value: (this: This, arg: P) => R,
_context: ClassMethodDecoratorContext<This, (this: This, arg: P) => R>,
): (this: This, arg: P) => R {
const memo = new Map<P, R>()
return function (arg) {
if (memo.has(arg)) {
return memo.get(arg)!
}
const output = value.call(this, arg)
memo.set(arg, output)
return output
}
}
class Fibonacci {
@memo
static of(value: number): number {
if (value == 0 || value == 1) {
return value
}
return Fibonacci.of(value - 1) + Fibonacci.of(value - 2)
}
}