Hi there,
I am working on the last project (cash register) of the JavaScript Algorithm Certification and I am completly stuck!
I know that I am close to the result but I don’t find the trick !
Could you help me, please?
My code below
function checkCashRegister(price, cash, cid) {
// Create an array with the amount for each currency unit in the same order as in example
let currencyAmount = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100];
// Add this amount to cid with the exact number of each currency there are in cid
let newCid = [];
for (let i = 0; i < currencyAmount.length; i++) {
newCid.push(cid[i].concat(currencyAmount[i]).concat(Math.round(cid[i][1]/currencyAmount[i] * 100) / 100));
}
console.log(newCid);
// Create a function to calculate the total of register (cid)
function totalInRegister(arr) {
let register = 0;
for (let i = arr.length-1; i >= 0; i--) {
register += arr[i][1];
}
return Math.round(register * 100) / 100;
}
console.log("Total in register : " + totalInRegister(cid) + "$");
// Create a variable to store the amount to return back
let cashToGive = cash - price;
console.log("Cash to give : " + cashToGive + "$");
// Write the three conditions asked
let changeArr = [];
if (totalInRegister(cid) < cashToGive) {
return {
status: "INSUFFICIENT_FUNDS",
change: []
};
} else if (totalInRegister(cid) == cashToGive) {
return {
status: "CLOSED",
change: cid
};
} else {
for (let i = newCid.length-1; i >= 0; i--) {
let value = 0;
while (newCid[i][1] > 0 && cashToGive >= newCid[i][2]) {
console.log("Cid[i][1] " + newCid[i][1]);
cashToGive -= newCid[i][2];
console.log("Cid[i][2] " + newCid[i][2]);
cashToGive = Math.round(cashToGive * 100) / 100;
newCid[i][1] -= newCid[i][2];
value += newCid[i][2];
console.log("New cash to give : " + cashToGive);
console.log("Value : " + value);
}
if (value > 0) {
changeArr.push([newCid[i][0], value]);
}
}
}
}
console.log(checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 0.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]));
Thanks in advance !
Have a nice day and take care
Manon