Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const MEMOIZED_VALUE_KEY = "_memoizedValue";
- const notMemoized = {};
- export function memoize(expirationTimeMs = 30000) {
- return (target: any, propertyName?: string, descriptor?: TypedPropertyDescriptor<any>) => {
- if (!propertyName) {
- memoizeClass(target, expirationTimeMs)
- } else if (descriptor.value != null) {
- memoizeImpl(expirationTimeMs, descriptor, "value");
- } else {
- throw "Only put the @memoize decorator on a class or method.";
- }
- };
- }
- export function notMemoize(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<any>) {
- const className = target.constructor;
- if (notMemoized[className]) {
- notMemoized[className].push(propertyName);
- } else {
- notMemoized[className] = [propertyName];
- }
- }
- export function clearMemoizedValue(method) {
- delete method[MEMOIZED_VALUE_KEY];
- }
- function memoizeClass(target: any, expirationTimeMs: number) {
- const names = Object.getOwnPropertyNames(target.prototype);
- for (const name of names) {
- const needMemoize =
- name !== "constructor"
- && typeof target.prototype[name] == "function"
- && (!notMemoized[target] || !notMemoized[target].includes(name));
- if (needMemoize) {
- memoizeImpl(expirationTimeMs, target.prototype, name);
- }
- }
- }
- function memoizeImpl(expirationTimeMs: number, target: Object, methodName: string) {
- const originalMethod = target[methodName];
- let fn = function (...args: any[]) {
- if (!fn[MEMOIZED_VALUE_KEY]) {
- fn[MEMOIZED_VALUE_KEY] = originalMethod.apply(this, args);
- setTimeout(() => clearMemoizedValue(fn), expirationTimeMs);
- }
- return fn[MEMOIZED_VALUE_KEY];
- };
- target[methodName] = fn;
- }
Advertisement
Add Comment
Please, Sign In to add comment