Home > Blockchain >  Shipping weight Calculation
Shipping weight Calculation

Time:10-08

I need to calculate the shipping price based on the product weight.

  • Shipping Price $1 Weight 0-.5
  • Shipping Price $2 Weight .6-1
  • Shipping Price $3 Weight 2-3
  • Shipping Price $4 Weight 4-5
  • Shipping Price $5 Weight 6-10
  • Shipping Price $6 Weight 11-25.

If I enter a weight between 1 and 10, the shipping price shows incorrectly. How do I fix these errors?

function sprice()
{  
    let a=0.5; let b=1; let c=3;    let d=5;    let e=10;   let f=25;
    
    let g=1; //0-.5
    let h=2; //.6-1
    let i=3; //2-3
    let j=4; //4-5
    let k=5; //6-10
    let l=6; //11-25
    
    let z=0;
    let inc=0;  

    let p=document.getElementById("number").value;  
    let s=25;
    
    while(p>0)
        {
            if(p<=a){           
                z =g;
            }if(p<=b){
                z =h;
            }if(p<=c){
                z =i;
            }if(p<=d){
                z =j;
            }if(p<=e){
                z =k;
            }if(p<=f) {
                z =l;
            }
              inc;          
            let y= (inc*z);
            document.getElementById("ans").innerHTML = "$" y;           
            p -= s;
          }           
} 
<form>  
Enter Weight:<input type="text" id="number" name="number"/><br/>  
<input type="button" value="get" onclick="sprice()"/>  
</form> </br>   

<p>Shipping Price:<span id="ans"></span></p>

CodePudding user response:

Logic

  • Check if user input is grater than 25
  • If yes take the quantity as 25 or else take the same value of user input
  • Calculate the value using if else if conditions as mentioed in your question
  • Decrement 25 from the user input.
  • Run the logic in loop till the user input is less than zero.

The issue that you had was you had to use else if instead of simple else, because if you enter a value, say 0.1, it satisfies all the if conditions. And the sum will be wrong . Also you dont have to multiply your increment index with the sume like y = (inc*z);. You just need to keep on adding the sum in a loop decrementing 25 each time while executing the loop.

Working Fiddle

function sprice() {
  let a = 0.5; let b = 1; let c = 3; let d = 5; let e = 10; let f = 25;

  let g = 1; //0-.5
  let h = 2; //.6-1
  let i = 3; //2-3
  let j = 4; //4-5
  let k = 5; //6-10
  let l = 6; //11-25

  let z = 0;

  let userInput =  document.getElementById("number").value;
  let s = 25;
  let quantity = 0;

  while (userInput > 0) {
    quantity = userInput > s ? s : userInput;
    if (quantity <= a) {
      z  = g;
    } else if (quantity <= b) {
      z  = h;
    } else if (quantity <= c) {
      z  = i;
    } else if (quantity <= d) {
      z  = j;
    } else if (quantity <= e) {
      z  = k;
    } else if (quantity <= f) {
      z  = l;
    }
    userInput -= s;
  }
  document.getElementById("ans").innerHTML = "$"   z;
}
<form>
  Enter Weight:<input type="text" id="number" name="number" /><br />
  <input type="button" value="get" onclick="sprice()" />
</form> </br>

<p>Shipping Price:<span id="ans"></span></p>

CodePudding user response:

You should be able to simplify your logic here, creating a function getShippingPrice() to get the shipping price for a given weight, then adding to the total price until all the weight is accounted for:

function sprice()
{  
    let weight = Number(document.getElementById("number").value);
    let s = 25;
    
    let totalPrice = 0;
    while (weight > 0) {
       totalPrice  = getShippingPrice(weight);
       weight -= s;
    }    
    document.getElementById("ans").innerHTML = "$"   totalPrice;      
}

function getShippingPrice(weight) {
    if (weight <= 0.5 ) return 1;
    if (weight <= 1 )   return 2;
    if (weight <= 3 )   return 3;
    if (weight <= 5 )   return 4;
    if (weight <= 10 )  return 5;
    return 6;
}
    
<form>  
Enter Weight:<input type="text" id="number" name="number"/><br/>  
<input type="button" value="get" onclick="sprice()"/>  
</form> </br>   

<p>Shipping Price:<span id="ans"></span></p>

CodePudding user response:

Here is a much more clean, reliable and scalable solution. I think the code is fairly simple so I won't explain it. But if you don't understand anything feel free ask me :)

// Add more categories if you need
const categories = [{
    price: 1,
    range: [0, 0.5]
  },
  {
    price: 2,
    range: [0.6, 1]
  },
  {
    price: 3,
    range: [2, 3]
  },
  {
    price: 4,
    range: [4, 5]
  },
  {
    price: 5,
    range: [6, 10]
  },
  {
    price: 6,
    range: [11, 25]
  },
];

const [priceForMaxWeight, maxWeight] = categories.reduce(
  ([maxPrice, maxWeight], category) => {
    const [min, max] = category.range;
    if (min < 0 || max < 0 || min === max || min > max)
      throw new Error(`Invalid range: [${min}, ${max}]`);
    return max > maxWeight ? [category.price, max] : [maxPrice, maxWeight];
  }, [Infinity, -Infinity]
);

function getPrice(weight) {
  const isInRange = (value, [min, max]) => value >= min && value <= max;

  for (let i = 0; i < categories.length; i  ) {
    const {
      price,
      range
    } = categories[i];
    if (isInRange(weight, range)) return price;
  }

  throw new Error(`Weight: ${weight} doesn't fall into any category.`);
}

function calculatePrice(weight) {
  if (weight < 0) throw new Error(`Invalid weight: ${weight}`);

  if (weight > maxWeight)
    return priceForMaxWeight   calculatePrice(weight - maxWeight);
  return getPrice(weight);
}

// Interacting with dom
const calculateButton = document.getElementById("btn");
const result = document.getElementById("result");
const weightInput = document.getElementById("weight");

calculateButton.addEventListener("click", () => {
  const weight = Number(weightInput.value);
  result.innerText = calculatePrice(weight)   "$";
});
<p>Enter Weight:</p>
<input id="weight" type="number" min="0" /><br />
<button id="btn">Calculate Price</button>

<p>Price: <span id="result">0$</span></p>

  • Related