Crezzer7
Crezzer7

Reputation: 2335

Javascript - making this code efficient

Its a relatively simple question however I wanted to see how other people would tackle the below issue:

  1. A user can enter (x) quantity in to text box txtUserInput

so for example UserInput = 14

  1. 1 box can contain upto 4 items.

so based on the above txtUserInput, I want the program to calculate how many boxes are required, (in this case the answer would be 4 boxes, with 2 spaces remaining in the final box.

below is an example of the code in its basic form:

var itemsCount = txtUserInput;
var boxes = 0;

if (itemsCount <=4) {
boxes ++;
}

else if (itemsCount <=8 && >4) {
boxes += 2;
}

as you can see, I could repeat this over and over again to get the correct result but it would become very tedious and a lot longer than it requires...

So using JavaScript how can I put this into an array/loop and get boxes to give me my desired output?

thankyou for your help

Upvotes: 0

Views: 74

Answers (3)

Matthew de Nobrega
Matthew de Nobrega

Reputation: 306

You can use Math.ceil to round up after dividing the number of items by the size of the boxes (in this case 4);

var boxes = Math.ceil(txtUserInput/4);

Javascript's type coercion will handle an empty input (if txtUserInput is null) as zero automatically.

Upvotes: 1

Guffa
Guffa

Reputation: 700670

With your approach of checking how many boxes are needed, you would use a loop instead of having code for all possible number of boxes:

var boxes = 0;
while (itemsCount > 0) {
  boxes++;
  itemsCount -= 4;
}

However, you don't need a loop for this. You can just divide the number of items by four, and make sure that any fraction in the result causes another box to be used by rounding up:

var boxes = Math.ceil(itemsCount / 4);

For example dividing 14 by four gives the result 3.5, and rounding up gives you 4.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382384

Don't loop, do a division and then round up:

var boxes = Math.ceil(itemsCount / 4);

Upvotes: 5

Related Questions