From 57d64f30e30b57ba5dc035fcaf38895d775412bd Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Mon, 13 Feb 2023 14:27:35 +0100 Subject: Improve channel's avatar display performance --- client/src/app/helpers/utils/index.ts | 1 + client/src/app/helpers/utils/simple-memoize.ts | 49 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 client/src/app/helpers/utils/simple-memoize.ts (limited to 'client/src/app/helpers') diff --git a/client/src/app/helpers/utils/index.ts b/client/src/app/helpers/utils/index.ts index f821985c9..afa8f8f5c 100644 --- a/client/src/app/helpers/utils/index.ts +++ b/client/src/app/helpers/utils/index.ts @@ -2,6 +2,7 @@ export * from './channel' export * from './date' export * from './html' export * from './object' +export * from './simple-memoize' export * from './dom' export * from './upload' export * from './url' diff --git a/client/src/app/helpers/utils/simple-memoize.ts b/client/src/app/helpers/utils/simple-memoize.ts new file mode 100644 index 000000000..e8292793f --- /dev/null +++ b/client/src/app/helpers/utils/simple-memoize.ts @@ -0,0 +1,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) => { + 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) { + 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 + } +} -- cgit v1.2.3