Reputation: 63
This is my code
const renderEventStartEndDate = entry => {
const { classes } = props;
const isValidStartDate = isDateValid(entry.startDate);
const isValidEndDate = isDateValid(entry.endDate);
if (isValidStartDate && isValidEndDate && entry.startDate !== entry.endDate) {
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.startDate).toUpperCase()}
{` TO ${getFormattedEventDate(entry.endDate).toUpperCase()}`}
</div>
);
} else if (entry.startDate === entry.endDate && isValidStartDate && isValidEndDate) {
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.startDate).toUpperCase()}
</div>
);
} else if ((isValidStartDate && !isValidEndDate) || (!isValidStartDate && isValidEndDate)) {
if (isValidStartDate)
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.startDate).toUpperCase()}
</div>
);
if (isValidEndDate)
return (
<div className={classes.textContainer}>
{getFormattedEventDate(entry.endDate).toUpperCase()}
</div>
);
}
I have an application and I want to reuse the above code so I am especially looking to reduce the return code here. I want to make a function like the one below and then use it in different components.
export const isDateValid = date => {
const dateObj = new Date(date);
return !isNaN(dateObj.getTime());
};
Upvotes: 0
Views: 59
Reputation: 8125
Lot of refactor need, You can first separate, Business logic from View. Like parsing dates and creating string.
Sample:
const getDate = entry => {
const isValidStartDate = isDateValid(entry.startDate);
const isValidEndDate = isDateValid(entry.endDate);
if (isValidStartDate && isValidEndDate && entry.startDate !== entry.endDate) {
return `${getFormattedEventDate(
entry.startDate
).toUpperCase()} TO ${getFormattedEventDate(entry.endDate).toUpperCase()}`;
} else if (
entry.startDate === entry.endDate &&
isValidStartDate &&
isValidEndDate
) {
return `${getFormattedEventDate(entry.startDate).toUpperCase()}`;
} else if (
(isValidStartDate && !isValidEndDate) ||
(!isValidStartDate && isValidEndDate)
) {
if (isValidStartDate)
return `${getFormattedEventDate(entry.startDate).toUpperCase()} `;
if (isValidEndDate)
return `${getFormattedEventDate(entry.endDate).toUpperCase()}`;
}
};
const renderEventStartEndDate = entry => {
const { classes } = props;
return <div className={classes.textContainer}>{getDate(entry)}</div>;
};
Upvotes: 1