Advertisements
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');
}
>Solution :
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:
...
}