I'm trying to write a constructor function that generates instances of a user. One of the properties of the user class is an array of the user's hobbies. I'd like my constructor to have a method that generates a string representation of the array of hobbies provided to the constructor function. The goal is to create a grammatically correct sentence containing the hobbies of the Person instance, so if interests = ['hiking', 'biking', 'skiing'] the Person.bio() method will alert something like: This person's interests are: hiking, biking and skiing. I am trying to account for an array of unknown length being passed to the constructor.
I haven't used .reduce() much but from the little bit of testing I've done, this seems to do what I want it to do. I'm just looking for any critiques on how to make things more readable or performant!
Below is a stripped down version of the constructor function (missing things like name, age, etc. for clarity).
function Person(interests = []) {
this.interests = interests;
this.hobbiesSentence = interests.reduce((hobbyString, hobby, index, interests) => {
switch(index) {
case (interests.length - 1):
return hobbyString += `${hobby}.`
case (interests.length - 2):
return hobbyString += `${hobby} and `
default:
return hobbyString += `${hobby}, `
}
}, '');
this.bio = function () {
alert(`This person's interests are: ${this.hobbiesSentence}`)
};
}
As I'm writing this, I could see a case for making the function exist but not necessarily creating/storing the sentence unless the bio() method is called. Any other ideas? Thanks in advance.