I’ve tried to follow all your recommendations and I think that I have only 2 issues for now:
-
If change includes one or more pennies, I still lose 1 penny elsewhere (for example, if change due is 1 penny, I don’t have any result at all, if change due is 2 pennies, the result is 1 penny…
-
I’d like to use map method to multiply the cid array instead of writing it directly, but the code doesn’t allow me to do that (when I log the modified cid array, console shows 9 “undefined” lines instead of the array values.
May I ask you to help me with this, too, please?
const button = document.getElementById("purchase-btn");
let price = 1.87;
let cid = [
['PENNY', 1.01],
['NICKEL', 2.05],
['DIME', 3.1],
['QUARTER', 4.25],
['ONE', 90],
['FIVE', 55],
['TEN', 20],
['TWENTY', 60],
['ONE HUNDRED', 100]
];
function checkRegister() {
const changeDue = document.getElementById("change-due");
let change = {stat: "", changeRegex: ""};
let resultedArr = [
[' ONE HUNDRED: $', 0],
[' TWENTY: $', 0],
[' TEN: $', 0],
[' FIVE: $', 0],
[' ONE: $', 0],
[' QUARTER: $', 0],
[' DIME: $', 0],
[' NICKEL: $', 0],
[' PENNY: $', 0],
];
const cidMult =
[
['PENNY', 101],
['NICKEL', 205],
['DIME', 310],
['QUARTER', 425],
['ONE', 9000],
['FIVE', 5500],
['TEN', 2000],
['TWENTY', 6000],
['ONE HUNDRED', 10000]
];
const currencyKeyMult = [10000, 2000, 1000, 500, 100, 25, 10, 5, 1,];
const dicMult = cidMult.reverse();
const cash = document.getElementById("cash");
let dicTotal = 0;
for (let i = 0; i < dicMult.length; i++) {
dicTotal += dicMult[i][1];
};
let user_input = Number(cash.value);
let result = ((user_input - price) * 100);
if (user_input < price) {
alert("Customer does not have enough money to purchase the item");
} else if (user_input === price) {
changeDue.textContent = "No change due - customer paid with exact cash";
} else {
for (let i = 0; i < dicMult.length; i++) {
while (dicMult[i][1] > 0) {
if(result - currencyKeyMult[i] >= 0) {
resultedArr[i][1] += currencyKeyMult[i] / 100;
result -= currencyKeyMult[i];
dicMult[i][1] -= currencyKeyMult[i];
} else {break}
const str = String(resultedArr);
const regex = str.replaceAll(",", "");
console.log(resultedArr);
if (result !== 0) {
change.stat = "Status: INSUFFICIENT_FUNDS";
} else if (result === 0 && dicTotal === (result / 100)) {
change.stat = "CLOSED";
change.changeRegex = regex;
} else {
resultedArr = resultedArr.filter(e => e[1] !== 0);
change.stat = "OPEN";
change.changeRegex = regex;
}
}
changeDue.textContent = change.stat;
changeDue.textContent += change.changeRegex;
}
}
}
button.addEventListener("click", checkRegister);