Reputation: 569
I am looping through an array of objects and trying to see if there is a better way to write this (i feel like there is).
This is my function below.
getCallInfo = (callSch: any, security: any) => {
const callObj = {
CallTimingType: 'Not Callable',
isCheckMark: null,
};
if (!security.IsCallable) return callObj;
callSch.Calls.forEach((el: { CallTimingType: string }) => {
if (el.CallTimingType === CallTimingType.SpecificDates) {
callObj.CallTimingType = 'Discrete';
callObj.isCheckMark = true;
}
if (
el.CallTimingType === CallTimingType.AnyTime ||
el.CallTimingType === CallTimingType.Monthly ||
el.CallTimingType === CallTimingType.OnPaymentDates ||
el.CallTimingType === CallTimingType.AnyInterestAdjustmentDate
) {
callObj.CallTimingType = 'Continuous';
callObj.isCheckMark = true;
}
});
return callObj;
};
basically what is doing is returning the default object if security.IsCallable is false but if true looping through the array of objects and setting the default object to different values. What I am basically doing is trying to refactor this. CallTimingType
is an object with these enum values. Any thoughts?
Upvotes: 1
Views: 71
Reputation: 1835
You could rewrite your clause with switch case
operator to make it clear:
callSch.Calls.forEach((el: { CallTimingType: string }) => {
switch (el.CallTimingType) {
case CallTimingType.SpecificDates:
callObj.CallTimingType = 'Discrete';
callObj.isCheckMark = true;
break;
case CallTimingType.AnyTime:
case CallTimingType.Monthly:
case CallTimingType.OnPaymentDates:
case CallTimingType.AnyInterestAdjustmentD:
callObj.CallTimingType = 'Continuous';
callObj.isCheckMark = true;
break;
}
});
Alternatively, you could use Set
:
callSch.Calls.forEach((el: { CallTimingType: string }) => {
const discreteSet = new Set([CallTimingType.SpecificDates]);
const continuousSet = new Set([
CallTimingType.AnyTime,
CallTimingType.Monthly,
CallTimingType.OnPaymentDates,
CallTimingType.AnyInterestAdjustmentD,
]);
if (discreteSet.has(el.CallTimingType)) {
callObj.CallTimingType = 'Discrete';
callObj.isCheckMark = true;
} else if (continuousSet.has(el.CallTimingType)) {
callObj.CallTimingType = 'Continuous';
callObj.isCheckMark = true;
}
});
Upvotes: 1
Reputation: 13059
You could use Array.prototype.some() to iterate and test if el.CallTimingType
matches any value.
if (
el.CallTimingType === CallTimingType.AnyTime ||
el.CallTimingType === CallTimingType.Monthly ||
el.CallTimingType === CallTimingType.OnPaymentDates ||
el.CallTimingType === CallTimingType.AnyInterestAdjustmentDate
)
Can be rewritten as:
const callTimingTypes = [
CallTimingType.AnyTime,
CallTimingType.Monthly,
CallTimingType.OnPaymentDates,
CallTimingType.AnyInterestAdjustmentDate
];
if (callTimingTypes.some((t) => el.CallTimingType === t))
Upvotes: 2