Created
February 2, 2025 13:30
-
-
Save helabenkhalfallah/e0c73d429d998ab7ebc2d8d43d25fb07 to your computer and use it in GitHub Desktop.
Refactoring Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatUsersBadWay(users) { | |
// Keep only valid users: phone & email not null | |
for (let i = 0; i < users.length; i++) { | |
const user = users[i]; | |
if (user.email === null || user.phone === null) { | |
users.splice(i, 1); | |
} | |
} | |
// Sort by name alphabetically | |
users.sort(function (a, b) { | |
if (a.name < b.name) { | |
return -1; | |
} | |
if (a.name > b.name) { | |
return 1; | |
} | |
return 0; | |
}); | |
// Transform fields for UI display | |
users.forEach(function (user) { | |
if ( | |
user.address !== null && | |
user.address.zipcode !== null && | |
user.address.street !== null && | |
user.address.city !== null | |
) { | |
user.address = `Living at: ${user.address.zipcode} ${user.address.street} ${user.address.city}`; | |
} | |
if (user.phone !== null) { | |
user.phone = `Phone number: ${user.phone}`; | |
} | |
if ( | |
user.company !== null && | |
user.company.name !== null && | |
user.company.catchPhrase !== null && | |
user.company.bs !== null | |
) { | |
user.company = `Company: ${user.company.name.toUpperCase()} - ${user.company.catchPhrase.toLowerCase()}, ${user.company.bs}`; | |
} | |
}); | |
return users; | |
} | |
// Extracted helper function for formatting a single user | |
function formatUserDetails(user) { | |
return { | |
...user, | |
address: formatAddress(user.address), | |
phone: formatPhone(user.phone), | |
company: formatCompany(user.company), | |
}; | |
} | |
// Helper function: Formats Address | |
function formatAddress(address) { | |
return address | |
? `Living at: ${address.zipcode} ${address.street} ${address.city}` | |
: "Address unavailable"; | |
} | |
// Helper function: Formats Phone | |
function formatPhone(phone) { | |
return phone ? `Phone number: ${phone}` : "Phone unavailable"; | |
} | |
// Helper function: Formats Company Info | |
function formatCompany(company) { | |
return company | |
? `Company: ${company.name.toUpperCase()} - ${company.catchPhrase.toLowerCase()}, ${company.bs}` | |
: "Company details unavailable"; | |
} | |
function formatUsers(users) { | |
return users | |
.filter(user => user.email !== null && user.phone !== null) | |
.sort((a, b) => a.name.localeCompare(b.name)) | |
.map(formatUserDetails); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment