blob: e8292793fd0630480cb61fdb5e8718df2fb8bcee (
plain) (
blame)
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
49
|
/**
*
* Simple memoize only support methods that accept 0 or 1 argument
* You can easily use it adding @SimpleMemoize just above the method name
*
*/
export function SimpleMemoize () {
const store = new Map()
return (_target: object, _propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
if (descriptor.value != null) {
descriptor.value = getNewFunction(descriptor.value, store)
return
}
throw new Error('Only put a Memoize() decorator on a method accessor.')
}
}
function getNewFunction (originalMethod: () => void, store: Map<any, any>) {
return function (this: any, ...args: any[]) {
if (args.length > 1) {
throw new Error('Simple memoize only support 0 or 1 argument')
}
let returnedValue: any
if (args.length > 0) {
const hashKey = args[0]
if (store.has(hashKey)) {
returnedValue = store.get(hashKey)
} else {
returnedValue = originalMethod.apply(this, args)
store.set(hashKey, returnedValue)
}
} else {
if (store.has(this)) {
returnedValue = store.get(this)
} else {
returnedValue = originalMethod.apply(this, args)
store.set(this, returnedValue)
}
}
return returnedValue
}
}
|