I have come a long way but there is one detail I need clarification about. The project’s third test results are different than mine. While I have not completely finished the challenge, I’m very close.
Why is the third challenge moving on from TWENTY at 60$ rather than at 80$? Isn’t the objective to give as much change w/ highest denominator and then move on from there? The third test has Cash = 3 and CID = 100. The Change Due is 96.74, which TWENTY can go into 4 times but the third test has this at 3 times or $60 dollars.
Code so far. Please note, I have added a console log for the results I am getting and plan to clean up the NULL values in the other tests:
function checkCashRegister(price, cash, cid) {
var currency = [["PENNY", .01], ["NICKEL",.05], ["DIME",.10], ["QUARTER",.25], ["ONE",1], ["FIVE",5], ["TEN",10], ["TWENTY",20], ["ONE HUNDRED",100]];
var change;
// Here is your change, ma'am.
let avail = [];
let availSum = avail.reduce((a, b) => a + b, 0); //will use later
let changeDue = cash - price;
let words = [];
let divisors = [];
let finalDivisors = [];
//loop through currency array
for (var j=currency.length-1;j>=0;j--) {
//get divisors and words
if (changeDue / currency[j][1] > 1) {
divisors.push(currency[j][1]);
words.push(currency[j][0]);
//first index of divisors
if (divisors.indexOf(divisors[j]) === 0 ) {
while (changeDue > .01) {
//multiply divisor by changeDue/divisors[j]
var reduceDivisor = divisors[j] * Math.floor(changeDue / divisors[j]);
//Subtract current changeDue with result from reduceDivisor
changeDue -= reduceDivisor;
finalDivisors.push(reduceDivisor );
//remove current number to get a new index
divisors.shift();
}
//For last num in array. .01 decimal fix and replace
var last = finalDivisors[finalDivisors.length -1];
var lastNum = parseFloat((last + changeDue).toFixed(2));
var replaced = finalDivisors.splice(-1, 1, lastNum);
}
}
}
//insert final numbers into words array
let newfinal = [];
for (var i=0;i<words.length;i++){
newfinal.push([words[i],finalDivisors[i]]);
}
console.log(newfinal);
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register