# Code review - Exact Change (Advanced Algorithm Scripting)

Code review - Exact Change (Advanced Algorithm Scripting)
0

#1

Just finished Exact Change in Advanced Algorithm Scripting and as it doesn’t have wiki article I would like someone to review my code:

``````function calculateAmount(array) {
return parseFloat(array.reduce(function(a, b) {
return a + b[1];
}, 0).toFixed(2));
}

function checkCashRegister(price, cash, cid) {
var billsValue = [0.01, 0.05, 0.10, 0.25, 1, 5, 10, 20, 100];
var changeArr = [];
var result = [];
var change = cash - price;
var cidAmount = calculateAmount(cid);

if (change > cidAmount) {
return "Insufficient Funds";
}
if (change === cidAmount) {
return "Closed";
}

var count = 0;
for (var i = billsValue.length - 1; i >= 0; i--) {
changeArr = [];
if (billsValue[i] <= change) {
changeArr.push(cid[i][0]); // Add bill's name to the array
count = 0;
while (billsValue[i] <= change && ((cid[i][1]) - count * billsValue[i]) >= billsValue[i]) {
change = parseFloat((change - billsValue[i]).toFixed(2));
count++;
}
count *= billsValue[i];
changeArr.push(count);
}
if (changeArr.length > 0) {
result.push(changeArr);
}
}
if (calculateAmount(result) < change) {
return "Insufficient Funds";
}
return result;
}

checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
// should return [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15.00], ["ONE", 1.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]]
``````

#2

Looks good. I wish I had thought to traverse the array in reverse like that.