Search code examples
javascriptreactjsincrement

How to increment x by y in react


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?


Solution

  • 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))