Oh, it’s not easier to read with Polacode, sorry… Here it is:
// 1. Calculate how much money is in the cash register
const calcAmountInRegister = array => {
let amount = 0;
for (element of array) {
amount += element[1];
}
return Number(amount.toFixed(2));
};
// 2. Calculate the amount to give back
const calcGiveBack = (price, cash) => {
let giveBack = cash - price;
return Number(giveBack.toFixed(2));
};
// 3. Check for INSUFFICIENT_FUNDS case
const isThereEnough = (amountIn, amountOut) => {
let notEnough;
notEnough =
amountIn - amountOut < 0
? {
status: 'INSUFFICIENT_FUNDS',
change: [],
}
: 'Indeed, there is enough!';
return notEnough;
};
// 4. Add the value of each bill and coin to the passed array
const addValueToCid = (cid, value) => {
for (let i = 0; i < value.length; i++) {
cid[i].push(value[i]);
}
return cid;
};
// 5. Calculate the number of bills or coins for each currency unit
const howMuchPerCurrencyUnit = array => {
for (element of array) {
element.push(Number((element[1] / element[2]).toFixed(2)));
}
return array;
};
const changeFunction = (back, array) => {
let change = {
status: 'OPEN',
change: [],
};
for (let i = array.length - 1; i >= 0; i--) {
if (back >= array[i][2]) {
let sum = 0;
while (back >= array[i][2] && array[i][3] !== 0) {
sum += array[i][2];
array[i][3] -= 1;
back = (back - array[i][2]).toFixed(2);
back = Number(back);
}
change.change.push([array[i][0], sum]);
} else {
continue;
}
back = Number(back.toFixed(2));
}
return change;
};
function checkCashRegister(price, cash, cid) {
let amountInRegister, giveBack, checkForFunds, newCid, change;
// 1. Store the value of each bill and coin
const valueOfEach = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100];
amountInRegister = calcAmountInRegister(cid);
giveBack = calcGiveBack(price, cash);
checkForFunds = isThereEnough(amountInRegister, giveBack);
newCid = addValueToCid(cid, valueOfEach);
newCid = howMuchPerCurrencyUnit(newCid);
change = changeFunction(giveBack, newCid);
return change;
}