michael-38
michael-38

Reputation: 43

Calculating change using an object - javascript

I'm trying to create a function that takes in a total and the cash given for that total, and then return the correct amount of change in an object.

In my incomplete code below, I can only get the tenDollar to calculate correctly and the fiveDollar is not counting properly (there should be 1 tenDollar, 1 fiveDollar returned). What am I missing here?

var calculateChange = function(total, cash) {
var totalIndex = total;
var cashIndex = cash;
var roundedChange = Math.round((cash - total) * 100) / 100;

var cashCount = {tenDollar:0, fiveDollar:0, twoDollar:0, oneDollar:0, 
quarter:0, dime:0, nickel:0, penny:0};

for (var i=0; i===0; ) {
i = roundedChange;
if (i-10 >= 0) {
  cashCount.tenDollar += 1;
  i = roundedChange-10;
}
else if (i-5 >= 0) {
  cashCount.fiveDollar += 1;
  i = roundedChange-5;
}
}
return cashCount;
}

console.log(calculateChange(1.87, 20));

Upvotes: 2

Views: 379

Answers (2)

JLRishe
JLRishe

Reputation: 101748

To fix your attempt:

  • Fix the loop so that it loops until i is zero instead of stopping when it's not zero.
  • Change the code so it subtracts from i instead of from roundedChange

The following calculates the expected result:

var calculateChange = function(total, cash) {
  var totalIndex = total;
  var cashIndex = cash;
  var roundedChange = Math.round((cash - total) * 100) / 100;

  var cashCount = {
    tenDollar: 0,
    fiveDollar: 0,
    twoDollar: 0,
    oneDollar: 0,
    quarter: 0,
    dime: 0,
    nickel: 0,
    penny: 0
  };

  var i = roundedChange;
  while (i > 0) {
    if (i - 10 >= 0) {
      cashCount.tenDollar += 1;
      i -= 10;
    }
    else if (i - 5 >= 0) {
      cashCount.fiveDollar += 1;
      i -= 5;
    }
  }
  return cashCount;
}

console.log(calculateChange(5, 50));

Upvotes: 1

Arthur Guiot
Arthur Guiot

Reputation: 721

I fixed your code using a much better method. Basically, using a bunch of Math.floor and modulo division, I got this result:

const calculateChange = (total, cash) => {
    const cashIndex = cash;
    const roundedChange = Math.round((cash - total) * 100) / 100;
    return {
        tenDollar: Math.floor(roundedChange / 10),
        fiveDollar: Math.floor((roundedChange % 10) / 5),
        twoDollar: Math.floor((roundedChange % 5) / 2),
        oneDollar: Math.floor(roundedChange % 2),
        quarter: Math.floor((roundedChange % 1) * 4),
        dime: Math.floor((roundedChange % 0.25) * 10),
        nickel: Math.floor((roundedChange % 0.1) * 20),
        penny: Math.floor(Math.round(roundedChange % 0.05 * 100))
    };
};

P.S. I also converted your code to modern JavaScript 😊. If you're more familiar with old JavaScript, you can use Babel to translate.

Upvotes: 1

Related Questions