Hello all,
My below code block works fine on my local editor for every testing scenarios. However, interestingly can’t pass any testing scenarios on freeCodeCamp.
Can somebody tell me what is wrong??
function checkCashRegister(price, cash, cid) {
let aCid = [
["PENNY", 0.01],
["NICKEL", 0.05],
["DIME", 0.1],
["QUARTER", 0.25],
["ONE", 1],
["FIVE", 5],
["TEN", 10],
["TWENTY", 20],
["HUNDRED", 100]
],
fDiff = 0,
fTempDiff = 0,
fQuotient = 0,
fChangeTemp = 0,
fSumAmount = 0;
aCidTemp = [];
fTempDiff = fDiff = cash - price;
// console.log(fDiff);
// sort the lists upside down to start with the highest change
cid = cid.reverse();
aCid = aCid.reverse();
for (let change in cid) {
fChangeTemp = 0;
fQuotient = 0;
if (fDiff > cid[change][1]) { // if the found diff greater than the change in the drawer
// subtract the found change from the difference
fDiff = (fDiff - cid[change][1]).toFixed(2);
aCidTemp.push(cid[change]);
// console.log(fDiff);
} else if (fDiff > aCid[change][1]) { // if the found diff greater than the currency unit itself (ex. 5 bucks in total 55)
fQuotient = cid[change][1] / aCid[change][1]; // find how many change we have of that currency unit
while (fQuotient && fDiff >= aCid[change][1]) {
fDiff = (fDiff - aCid[change][1]).toFixed(2);; // subtract the currency unit
fChangeTemp += aCid[change][1]; // collect the currency unit at its times
if (Math.floor(fChangeTemp) !== fChangeTemp) { // if number is decimal, get only the last 2 decimals
fChangeTemp = parseFloat(fChangeTemp.toFixed(2));
}
cid[change][1] = fChangeTemp; // change the change in the drawer amount
// console.log(fDiff);
fQuotient--;
}
aCidTemp.push(cid[change]); // collect and return the changed drawer amount
}
}
let bOpen = false;
aCidTemp.reverse(); // upside down the changes in the drawer
// console.log(aCidTemp);
if (fDiff > 0) {
aCidTemp = { status: "INSUFFICIENT_FUNDS", change: [] };
} else if (parseInt(fDiff) === 0) {
for (let i in cid) {
// if there more money than return
fSumAmount += cid[i][1];
}
if (fSumAmount.toFixed(2) === fTempDiff.toFixed(2)) {
bOpen = false; // CLOSED : return and change in the drawer are equal
} else {
bOpen = true; // OPEN : more change in the drawer than the return
}
if (bOpen) {
for (let i in aCidTemp) {
if (aCidTemp[i][1] === 0) {
delete aCidTemp[i][1];
}
}
aCidTemp.reverse(); // upside down the changes in the drawer
aCidTemp = { status: "OPEN", change: aCidTemp };
} else {
aCidTemp = { status: "CLOSED", change: aCidTemp };
}
}
console.log(aCidTemp);
return aCidTemp;
}
checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])
returns { status: 'OPEN', change: [ [ 'QUARTER', 0.5 ] ] } as expected.
Thanks in advance,
Merve