简体   繁体   中英

How to make a reusable function so that I keep the good practice of DRY?

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());
};

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>;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM