]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/helpers/utils/simple-memoize.ts
Don't display unknown information
[github/Chocobozzz/PeerTube.git] / client / src / app / helpers / utils / simple-memoize.ts
CommitLineData
57d64f30
C
1/**
2 *
3 * Simple memoize only support methods that accept 0 or 1 argument
4 * You can easily use it adding @SimpleMemoize just above the method name
5 *
6 */
7
8export function SimpleMemoize () {
9 const store = new Map()
10
11 return (_target: object, _propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
12 if (descriptor.value != null) {
13 descriptor.value = getNewFunction(descriptor.value, store)
14 return
15 }
16
17 throw new Error('Only put a Memoize() decorator on a method accessor.')
18 }
19}
20
21function getNewFunction (originalMethod: () => void, store: Map<any, any>) {
22 return function (this: any, ...args: any[]) {
23 if (args.length > 1) {
24 throw new Error('Simple memoize only support 0 or 1 argument')
25 }
26
27 let returnedValue: any
28
29 if (args.length > 0) {
30 const hashKey = args[0]
31
32 if (store.has(hashKey)) {
33 returnedValue = store.get(hashKey)
34 } else {
35 returnedValue = originalMethod.apply(this, args)
36 store.set(hashKey, returnedValue)
37 }
38 } else {
39 if (store.has(this)) {
40 returnedValue = store.get(this)
41 } else {
42 returnedValue = originalMethod.apply(this, args)
43 store.set(this, returnedValue)
44 }
45 }
46
47 return returnedValue
48 }
49}