简体   繁体   English

如何简化对象

[英]How to simplify object

I have an issue here where the code is quite heavy and quite hard to read imo.我在这里遇到一个问题,代码非常繁重且很难阅读 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');
    }

You can use Template Strings to simplify booking_name您可以使用模板字符串来简化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.变量名称的一致性也会更好,您可以选择其中一种变量命名样式,snake_case 或 camelCase。

Also now you can shorten expression key:value even more .现在您还可以进一步缩短表达式key:value


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 case会更好。

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

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.在这里,我们有一个基本的Booking对象,可用于构建所有类型的预订。 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 -在上面的函数中,可以清楚地看到每个输出都关联了Party信息 -

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 -以下是预订类型, HourlyDayOrMonthSingle -

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 -我们避免重复moment(...).format(...)并确保与mDatemTime的一致性 -

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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