Skip to content

Instantly share code, notes, and snippets.

@kevinbuhmann
Created April 20, 2022 19:05
Show Gist options
  • Save kevinbuhmann/4b1ce50efae965d5f06e6508511bdab6 to your computer and use it in GitHub Desktop.
Save kevinbuhmann/4b1ce50efae965d5f06e6508511bdab6 to your computer and use it in GitHub Desktop.
interface Property {
hasValue?: boolean;
lastInputPropertyValue?: any;
currentValue?: any;
}
export function ProjectProperty<T, K extends keyof T>(inputPropertyName: K, projectFn: (input: T[K]) => any) {
const propertySymbol = Symbol();
return (target: T, propertyKey: PropertyKey) => {
Object.defineProperty(target, propertyKey, { get: getValue });
};
function getProperty(instance: { [propertySymbol]: Property }) {
return instance[propertySymbol] || (instance[propertySymbol] = {});
}
function getValue(this: any) {
const property = getProperty(this);
const inputPropertyValue = this[inputPropertyName];
if (!property.hasValue || inputPropertyValue !== property.lastInputPropertyValue) {
property.hasValue = true;
property.lastInputPropertyValue = inputPropertyValue;
property.currentValue = projectFn(inputPropertyValue);
}
return property.currentValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment