Home > Back-end >  How to simplify object
How to simplify object

Time:07-18

I have an issue here where the code is quite heavy and quite hard to read imo.

I've simplified the code as much as I can but I was wandering if there's a way to simplify this code even further? Or maybe if there is any better terminology i could use for the comments? Any help is much appreciated, Thanks in advance!

    const hourly = rateType[1] === 'Hourly';
    const daily = rateType[1] === 'Day Pass';
    const monthly = rateType[1] === 'Monthly Pass';
    const single = passType === 'single';

    // -- For all payloads
    const data = {
      booking_name: username.first_name   ' '   username.last_name,
      number_of_people: numOfPeople,
    };
    // -- Hourly payload
    const hourlyPayload = {
      ...data,
      date: moment(mainDate).format('YYYY-MM-DD'),
      from: moment(timeFrom).format('hh:mm'),
      to: moment(timeUntil).format('hh:mm'),
    };
    // -- Daily or monthly payload
    const DayOrMonthPayload = {
      ...data,
      start_date: moment(startDate).format('YYYY-MM-DD'),
      end_date: moment(endDate).format('YYYY-MM-DD'),
    };
    // -- Single day payload
    const singleDayPayload = {
      ...data,
      dates: [moment(startDate).format('YYYY-MM-DD')],
    };

 // -- // CREATE_BOOKING_FN // -- //
    if (rateType) {
      setLoading(true);
      hourly // --||-- Hourly Action --||-- \\
        ? await addToCart(hourlyPayload, 'hourly', id, cartItems, () =>
            _handleAdded(
              fastCheckout ? fastCheckout : null,
              cb ? () => cb() : null,
            ),
          )
        : daily // --||-- Daily Action  --||-- \\
        ? await addToCart(
            single ? singleDayPayload : DayOrMonthPayload,
            single ? 'individual-dates' : 'daily',
            id,
            cartItems,
            () =>
              _handleAdded(
                fastCheckout ? fastCheckout : null,
                cb ? () => cb() : console.log('null'),
              ),
          )
        : monthly // --||-- Monthly Action  --||-- \\
        ? await addToCart(DayOrMonthPayload, 'monthly', id, cartItems, () =>
            _handleAdded(
              fastCheckout ? fastCheckout : null,
              cb ? () => cb() : console.log('null'),
            ),
          )
        : null;
      setLoading(false);
    } else {
      alert('Please select a rate');
    }

CodePudding user response:

You can use Template Strings to simplify booking_name

booking_name: `${username.first_name} ${username.last_name}`,

Also consistency in variable names would better, you could choose one of the variable naming styles, snake_case or camelCase.

Also now you can shorten expression key:value even more.


const data = {
  booking_name: `${username.first_name} ${username.last_name}`,
  number_of_people,
};

Also that ternary expression is very hard to read, I think switch case would better.

switch (type_of_date) {
  case hourly:
      ...
  case daily:
      ...
  case monthly:
      ...
  default:
      ...
}

CodePudding user response:

I would recommend using functions for avoiding repetition and creating data. Here we have a basic Booking object that can be used to construct all varieties of bookings. Fill in ___ as you see fit -

function Booking(type, ___) {
  switch (type) {
    case "Hourly"
      return { ...Party(___), ...Hourly(___) }
    case "DayOrMonth":
      return { ...Party(___), ...DayOrMonth(___) }
    case Single:
      return { ...Party(___), ...Single(___) }
    default:
      throw Error("invalid booking type: "   type)
  }
}

In the function above it's plain to see that each output has Party information associated -

function Party(user, number_of_people) {
  return {
    name: user.first_name   " "   user.last_name
    number_of_people
  }
}

Here are the booking types, Hourly, DayOrMonth and Single -

function Hourly(date, from, to) {
  return {
    date: mDate(date),
    from: mTime(from),
    to: mTime(to)
  }
}
function DayOrMonth(start, end) {
  return {
    start: mDate(start),
    end: mDate(end)
  }
}

function Single(date) {
  return {
    date: mDate(date)
  }
}

We avoid repetition of moment(...).format(...) and ensure consistency with mDate and mTime -

function mDate(t) {
  return moment(t).format("YYYY-MM-DD")
}

function mTime(t) {
  return moment(t).format("hh:mm")
}
  • Related