After creating a class, I realized that there is repeated logic that can be extracted into a method on the class to be reused by other properties of the class.
class Card {
protected readonly data: Data;
protected readonly user: User;
nameVal: string;
addressVal: string[];
constructor(raw_data: Data, user: User) {
this.data = raw_data;
this.user = user;
}
get name(): string {
if (!this.nameVal) {
this.nameVal = name_getter(this.data, this.user); // same parameters
}
return this.nameVal;
}
get address(): string[] {
if (!this.addressVal) {
this.addressVal = address_getter(this.data, this.user); // same parameters
}
return this.addressVal;
}
// The goal is to refactor the above logic and centralize it in a function like below
// maybe getter type would be something like this:
// type FieldValueGetter = (data: Data, user: User) => any;
getFieldValue(getter: FieldValueGetter, field: ?) { // Is there a way to define field type?
if(!field) {
this.field = getter(this.data, this.user);
}
return this.field;
}
}
Questions arise regarding defining the type for the field parameter in the getFieldValue method, as the value of the field may differ based on the field. However, the common factor is that the field would be part of the class.