Let's say I have a file data.js, which contains an array of some data that will be imported somewhere (eg. a React component).
EXAMPLE A:
const DATA = [
{
firstName: 'jim',
lastName: 'beam',
fullName: 'jim beam'
},
{
firstName: 'jack',
lastName: 'daniels',
fullName: 'jack daniels'
}
];
export default DATA;
Ok, cool. Thing is, we're writing out the fullName property, which could be gathered by combining firstName and lastName. This is a very trivial example for clarity, so bear with me. We could also do something like this:
EXAMPLE B:
const DATA = [
{ firstName: 'jim', lastName: 'beam' },
{ firstName: 'jack', lastName: 'daniels' }
];
export default DATA.map(person => ({
...person,
fullName: `${person.firstName} ${person.lastName}`
});
Heck, we could even do this!
EXAMPLE C:
const DATA = ['jim beam', 'jack daniels'];
export default DATA.map(person => {
const [firstName, lastName] = person.split(' ');
return {
firstName,
lastName,
fullName: person
};
};
So, imagine you have a huuge list of data, where multiple values could be derived from one initial value. My question is how would examples B and C differ from just hardcoding everything right off the bat like example A?
If you had hundreds of items, examples B and C could have much less overhead, a smaller file size, and can reduce potential typos... But, we're declaring an array and then exporting a different one, which I assume could have a performance dip? Thoughts?
How about a class with a getter that evaluates fullName on access?
It offers smaller in-memory size, and doesn't have a performance issue because fullName property of each datum is not computed until they are imported, and accessed.
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.firstName} ${this.lastName}`
}
}
let a = new Person('Charles', 'Martel');
console.log(a.fullName)
// expected result: "Charles Martel"
Your data can then be declared as the following.
const DATA = [
new Person('jim', 'beam'),
new Person('jack','daniels')
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With