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!
JavaScript
x
64
64
1
const hourly = rateType[1] === 'Hourly';
2
const daily = rateType[1] === 'Day Pass';
3
const monthly = rateType[1] === 'Monthly Pass';
4
const single = passType === 'single';
5
6
// -- For all payloads
7
const data = {
8
booking_name: username.first_name + ' ' + username.last_name,
9
number_of_people: numOfPeople,
10
};
11
// -- Hourly payload
12
const hourlyPayload = {
13
data,
14
date: moment(mainDate).format('YYYY-MM-DD'),
15
from: moment(timeFrom).format('hh:mm'),
16
to: moment(timeUntil).format('hh:mm'),
17
};
18
// -- Daily or monthly payload
19
const DayOrMonthPayload = {
20
data,
21
start_date: moment(startDate).format('YYYY-MM-DD'),
22
end_date: moment(endDate).format('YYYY-MM-DD'),
23
};
24
// -- Single day payload
25
const singleDayPayload = {
26
data,
27
dates: [moment(startDate).format('YYYY-MM-DD')],
28
};
29
30
// -- // CREATE_BOOKING_FN // -- //
31
if (rateType) {
32
setLoading(true);
33
hourly // --||-- Hourly Action --||-- \
34
? await addToCart(hourlyPayload, 'hourly', id, cartItems, () =>
35
_handleAdded(
36
fastCheckout ? fastCheckout : null,
37
cb ? () => cb() : null,
38
),
39
)
40
: daily // --||-- Daily Action --||-- \
41
? await addToCart(
42
single ? singleDayPayload : DayOrMonthPayload,
43
single ? 'individual-dates' : 'daily',
44
id,
45
cartItems,
46
() =>
47
_handleAdded(
48
fastCheckout ? fastCheckout : null,
49
cb ? () => cb() : console.log('null'),
50
),
51
)
52
: monthly // --||-- Monthly Action --||-- \
53
? await addToCart(DayOrMonthPayload, 'monthly', id, cartItems, () =>
54
_handleAdded(
55
fastCheckout ? fastCheckout : null,
56
cb ? () => cb() : console.log('null'),
57
),
58
)
59
: null;
60
setLoading(false);
61
} else {
62
alert('Please select a rate');
63
}
64
Advertisement
Answer
You can use Template Strings to simplify booking_name
JavaScript
1
2
1
booking_name: `${username.first_name} ${username.last_name}`,
2
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.
JavaScript
1
5
1
const data = {
2
booking_name: `${username.first_name} ${username.last_name}`,
3
number_of_people,
4
};
5
Also that ternary expression is very hard to read, I think switch case
would better.
JavaScript
1
11
11
1
switch (type_of_date) {
2
case hourly:
3
4
case daily:
5
6
case monthly:
7
8
default:
9
10
}
11