Issue
I have an Angular component that uses a type, what would be an easily readable solution to get one data on one case and the other in another?
The component could also be separated in two components, the phone component and the email component, but most of the logic albeit small would be duplicated.
var getContactInfo, hasContactInfo;
if(type === 'email') {
getContactInfo = function (profile) { return profile.getEmail()};
hasContactInfo = function (profile) { return profile.hasEmail()};
} else if(scope.type === 'phone') {
getContactInfo = function (profile) { return profile.getPhone()};
hasContactInfo = function (profile) { return profile.hasPhone()};
}
Solution
I would probably have used an object mapping the methods depending on the type:
const buildContactInfo = (getContactInfo, hasContactInfo) => ({ getContactInfo, hasContactInfo });
const contactInfoByType = {
email: buildContactInfo((profile) => profile.getEmail(), (profile) => profile.hasEmail()),
phone: buildContactInfo((profile) => profile.getPhone(), (profile) => profile.hasPhone())
};
Then, when calling:
const contactInfo = contactInfoByType[type];
if (!contactInfo) {
throw new Error(`No contact info matched type '${type}'`);
} else {
contactInfo.hasContactInfo(profile);
contactInfo.getContactInfo(profile);
}
Answered By - sp00m
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.