Refactoring example
by Vladymyr Shevchuk
JavaScript
// Existed code:
const favoriteContacts = () => {
return this.onlyOnline.favorites
? this.allUsersList.filter(
contact => contact.favorite === true
&& contact.presence === ONLINE
) : this.allUsersList.filter(
contact => contact.favorite === true
);
}
// Refactoring example 1
const favoriteContacts = () => {
const predicate = filterOnline => contact => {
const isFavorite = contact.favorite === true;
const isOnline = contact.presence === ONLINE;
return filterOnline ? isFavorite && isOnline : isFavorite;
};
return this.allUsersList.filter(predicate(this.onlyOnline.favorites));
}
// Refactoring example 2
const getFavoriteContacts = contacts => {
return contacts.filter(contact => contact.favorite === true);
}
const getFavoriteOnlineContacts = contacts => {
return contacts.filter(contact => contact.presence === ONLINE);
}
const getContacts = () => {
const favoriteContacts = getFavoriteContacts([{}, {}, {}]);
return this.onlyOnline.favorites ? getFavoriteOnlineContacts(favoriteContacts) : getFavoriteContacts();
}