This was the solution I ended up using with the help of a coworker and the answer above. Using if-statements with normal truthy checks removes the need to cast the optional parameters to string. Adding the last name last allowed me to remove the helper function to format the last name. Instead, we can just check that the array has an item already (first or middle name pushed) to know if we need to include the comma with the last name. Then we can use unshift to add it to the front of the array.
- Using if-statements with normal truthy checks removes the need to cast the optional parameters to string.
- Adding the last name at the end allowed me to remove the helper function that determines if a comma needs to be added.
- Instead, we can just check that the array has an item already (first or middle name pushed) to know if we need to include the comma with the last name.
- Then we can use
unshiftto add it to the front of the array.
I think this is a marked improvement in readability and reducing lines compared to the first version.
export function getLastNameFirstNameFullUserName(
user: { firstName?: string; lastName?: string; middleName?: string },
includeMiddleName = false,
): string {
const { firstName, lastName, middleName } = user;
const userNameArray: string[] = [];
if (firstName) {
userNameArray.push(firstName);
}
if (includeMiddleName && middleName) {
userNameArray.push(middleName);
}
if (lastName) {
const formattedLastName: string = userNameArray.length > 0 ? `${lastName},` : lastName;
userNameArray.unshift(formattedLastName);
}
return userNameArray.join(' ');
}