Recently, I received a set of user data from a JSON server response. Below is an example of the data:
var users = [
{id: 1, name: 'john', surname: 'smith'},
{id: 2, name: 'john', surname: 'smith'},
{id: 3, name: 'john', surname: 'smith'},
{id: 4, name: 'john', surname: 'smith'},
{id: 5, name: 'john', surname: 'smith'},
{id: 6, name: 'john', surname: 'smith'},
{id: 7, name: 'john', surname: 'smith'}
];
Throughout the application's business logic and templates (using handlebars), there is a need to have the full name of each user without repeatedly using the string concatenation logic name + ' ' + surname
.
To address this, I have implemented the following enhancement for these users by adding a custom function:
for(var i=0; length=users.length; i<length; i++) {
users[i].getFullName = function() {
return this.name + ' ' + this.surname;
}
}
Although this technique serves its purpose, some questions arise:
- Is there a more efficient way to achieve this? The objective is to find a solution that follows an object-oriented style rather than using something like
getFullNameOfUser(user)
. - While I can evaluate the time penalty of adding functions to all objects, how can I measure the memory impact of this approach? Methods such as JavaScript object size do not include functions in their calculations.