skip to Main Content

I’m calculating a fee based on a variable amount but the fee is based on a percentage of the amount with a set minimum of 600. I have the calculation working but wondered if there was a cleaner way to write it (math.max)?

export const calculateFee = (amount) => {
    const fixedAddons = 80 + 21 + 113 + 87 + 136;
    let fee;

    // If less than 600
    if (amount * 0.002 + 30 < 600) {
        console.log('fee', fee);
        // Set a minimum fee of 600
        fee = 600 + fixedAddons;
    } else {
        fee = amount * 0.002 + 30 + fixedAddons;
    }

    return fee;
};

4

Answers


  1. You can simplify your code by using Math.max() to compare the result of your fee calculation with the minimum fee of 600.

     const calculateFee = (amount) => {
        const fixedAddons = 80 + 21 + 113 + 87 + 136;
        let fee = amount * 0.002 + 30 + fixedAddons;
        fee = Math.max(fee, 600 + fixedAddons);
        return fee;
    };
    // example
    console.log(calculateFee(1000))
    Login or Signup to reply.
  2. If I understood your question correctly, you can simply use Math.max(), which will return the larger of the values you provide. So change your function to:

    export const calculateFee = (amount) => {
      const fixedAddons = 80 + 21 + 113 + 87 + 136;
      return Math.max(amount * 0.002 + 30, 600) + fixedAddons;
    };
    

    So if your fee calculation comes out to e.g. 500, you would end up with 600 (plus your fixed addons).

    Login or Signup to reply.
  3. An one-liner:

    const calculateFee = amount => Math.max(amount * 0.002 + 30, 600) + 80 + 21 + 113 + 87 + 136;
    console.log(calculateFee(1000))
    Login or Signup to reply.
  4. const calculateFee = (amount) => {
      const fixedAddons = 80 + 21 + 113 + 87 + 136;
      let fee;
      if (amount * 0.002 + 30 < 600) fee = 600 + fixedAddons;
      else fee = amount * 0.002 + 30 + fixedAddons;
      return fee;
    }
    
    console.log(calculateFee(1000))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search