Skip to content

Instantly share code, notes, and snippets.

@SteveStrong
Forked from dsherret/memoize-decorator.ts
Created March 19, 2018 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveStrong/547315b465940e8cd9a3b0cb226ed6dc to your computer and use it in GitHub Desktop.
Save SteveStrong/547315b465940e8cd9a3b0cb226ed6dc to your computer and use it in GitHub Desktop.
/**
* Caches the return value of get accessors and methods.
*
* Notes:
* - Doesn't really make sense to put this on a method with parameters.
* - Creates an obscure non-enumerable property on the instance to store the memoized value.
* - Could use a WeakMap, but this way has support in old environments.
*/
export function Memoize(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<any>) {
if (descriptor.value != null) {
descriptor.value = getNewFunction(descriptor.value);
}
else if (descriptor.get != null) {
descriptor.get = getNewFunction(descriptor.get);
}
else {
throw "Only put a Memoize decorator on a method or get accessor.";
}
}
let counter = 0;
function getNewFunction(originalFunction: () => void) {
const identifier = ++counter;
return function (this: any, ...args: any[]) {
const propName = `__memoized_value_${identifier}`;
let returnedValue: any;
if (this.hasOwnProperty(propName)) {
returnedValue = this[propName];
}
else {
returnedValue = originalFunction.apply(this, args);
Object.defineProperty(this, propName, {
configurable: false,
enumerable: false,
writable: false,
value: returnedValue
});
}
return returnedValue;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment