I have a variable weight
and a state value deliveryFee
.
As the value of weight
increases I need to increment the value of deliveryFee
according to this pattern:
Up to 2 kg => $3.40
Up to 5 kg => $3.80
Up to 10 kg => $4.20
And then for every additional 10kg I need to increment deliveryfee
by a further $3.50
I can do the first part easily using a ternary operator:
weight <= 2
? setDeliveryFee(3.4)
: weight <= 5
? setDeliveryFee(3.8)
: weight <= 10
&& setDeliveryFee(4.2)
But I can't work out how to increment the deliveryFee
by 3.5 every time weight
increases by an additional 10.
I know I could simply continue this pattern to achieve the result:
weight 1 <= 2
? setDeliveryFee(3.4)
: weight 1 <= 5
? setDeliveryFee(3.8)
: weight 1 <= 10
? setDeliveryFee(4.2)
: weight 1 <= 20
? setDeliveryFee(7.7)
: weight 1 <= 30
? setDeliveryFee(11.2)
: weight 1 <= 40
? setDeliveryFee(14.7)
&& weight 1 <= 50 && setDeliveryFee(18.2);
But since weight
could theoretically be any figure this is not fool proof so I really need a formula to accomplish this.
Is anyone able to help?
CodePudding user response:
You can use this equation 4.2 (Math.ceil((weight / 10) - 1) * 3.5)
, also I prefer to use if/else
or switch conditions rather than ternary operator in case there are a lot of cases for better readability.
const transform = (weight) => {
if (weight <= 2) {
return 3.4
} else if (weight <= 5) {
return 3.8
} else if (weight <= 10) {
return 4.2
} else {
return 4.2 (Math.ceil((weight / 10) - 1) * 3.5)
}
}
console.log(transform(5))
console.log(transform(10))
console.log(transform(20))
console.log(transform(30))
console.log(transform(40))
console.log(transform(50))
CodePudding user response:
You don't need to store deliveryFee
as React state; it is derived from weight
, so if you just directly calculate it from weight
, it will automatically update on every render to match the latest weight
.
const calculateDeliveryFee = weight => {
if(weight <= 2)
return 3.4;
if(weight <= 5)
return 3.8;
if(weight <= 10)
return 4.2;
// rest of your conditions
return 18.2;
}
The calculateDeliveryFee
will return the value of the first if
condition that is met, so you don't have to use else if
/else
. return 18.2
will execute if none of the previous conditions are true
. Then in your React component,
const deliveryFee = calculateDeliveryFee(weight);