I’m transforming data I receive from an API. The frontend requires some calculations to be displayed.
What is the proper way to handle the data transformation?
- Should I be defining a property to the object being passed? If so, why
- Is this a good use case to use setters and getters or would that be unnecessary?
const dogData = {
dog_name: "filo",
born_time: 1530983852,
coat_color: "brown"
};
class Dog {
constructor(data) {
//do I need to set this.dog to the data object, what's the benefit of doing so?
this.dog = data;
this.name = this.dog.dog_name;
// vs
this.name = data.dog_name;
//Should I use setters and getters?
this.color = this.dog.coat_color;
// vs
this._color = this.dog.coat_color;
this.age = this.calculateAge();
}
calculateAge() {
return Date.now().getTime() - this.dog.born_time;
}
//Is this a good case where I should using getters to access the properties or would that be superfluous?
//should I be setting the properties with setters in this case?
get color() {
return this._color;
}
}
const dog = new Dog(dogData)
Dog.dogdoesn't make sense. Just set the properties of the Dog (name & colour) and have the function for returning the age. Anything else is overkill, unless you can think of a reason to add them.born_timeto be changed after construction?Doginstance.