Hi need help with cash register projekt in the algorithms section.
I have bug with one of the tests. You can se below what the value
should be and what i value the functions output.
checkCashRegister(3.26, 100,
[["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100]])
/*
Should return:
{
status: "OPEN",
change: [["TWENTY", 60],
["TEN", 20],
["FIVE", 15],
["ONE", 1],
["QUARTER", 0.5],
["DIME", 0.2],
["PENNY", 0.04]]
}
*/
/*
Returns
{ status: 'OPEN',
change:
[ [ 'TWENTY', 60 ],
[ 'TEN', 20 ],
[ 'FIVE', 15 ],
[ 'ONE', 1 ],
[ 'QUARTER', 0.5 ],
[ 'DIME', 0.2 ],
[ 'PENNY', 0.03 ] ]
}
*/
const checkCashRegister = (price, cash, cid) => {
const registerStatus = {
open: "OPEN",
closed: "CLOSED",
insufficientFunds: "INSUFFICIENT_FUNDS"
}
const currency = {
PENNY: 0.01,
NICKEL: 0.05,
DIME: 0.10,
QUARTER: 0.25,
ONE: 1,
FIVE: 5,
TEN: 10,
TWENTY: 20,
"ONE HUNDRED": 100
}
let cashRegister = {status: "", change: []};
let changeNeeded = cash - price;
const changeAvailable = cid
.map(item => item[1])
.reduce( (sum, number) => sum += number, 0);
if (changeNeeded === changeAvailable) {
cashRegister.status = registerStatus.closed;
cashRegister.change = cid;
}
else if (changeNeeded > changeAvailable) {
cashRegister.status = registerStatus.insufficientFunds;
cashRegister.change = [];
}
else {
cashRegister.status = registerStatus.open;
cashRegister.change = [];
cid = cid.reverse();
for (let [coinName, coinValue] of cid) {
let currencyValue = currency[coinName];
let coinAmount = coinValue/currencyValue;
let coinToReturn = 0;
while (changeNeeded >= currencyValue && coinAmount ) {
changeNeeded -= currencyValue;
coinAmount --;
coinToReturn ++;
}
let coinToReturnValue = coinToReturn * currencyValue;
if (coinToReturn > 0) {
cashRegister.change.push([coinName, coinToReturnValue]);
}
}
}
return cashRegister;
}