Tell us what’s happening:
Hello, guys! My function is passing all test. But I started to think about 2nd condition (when status should be CLOSE). I wrote test in repl.it with one extra case: when price = 95, cash = 100 and cid has one 5$ for change. So which output should be in this case? This one:
{status: "CLOSED", change: [["FIVE", 5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["PENNY", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}
Also why should I push all zero units in output? Could somebody explain me, please? Thanks.
P.S. I’ll be glad if somebody criticize my code.
Your code so far
const checkCashRegister = (price, cash, cid) => {
const currencyTable = {
0: 10, 1: 50, 2: 100, 3: 250, 4: 1000,
5: 5000, 6: 10000, 7: 20000, 8: 100000,
};
let remainder = (cash - price) * 1000;
const iter = (change, i) => {
if (i === -1) return { ['status']: 'INSUFFICIENT_FUNDS', change: [] };
const notesNum = Math.floor(remainder / currencyTable[i]),
have = cid[i][1] * 1000,
need = currencyTable[i] * notesNum,
currNote = cid[i][0],
currentChange = (have > need ? need : have);
if (have === 0) {
newChange = [[currNote, 0], ...change];
return iter(newChange, i-1);
} else if (notesNum === 0) return iter(change, i-1);
remainder -= currentChange;
newChange = [...change, [currNote, currentChange/1000]];
if (remainder === 0) {
newChange = newChange.sort((a, b) => a[1] < b[1]);
const isClose = cidArr => cidArr.filter((unit, i) => unit[1] === newChange[i][1]).length > 0;
const status = newChange.length < 9 ? 'OPEN' : isClose(cid) ? 'CLOSED' : 'OPEN';
return { status, change: newChange };
}
return iter(newChange, i-1);
};
return iter([], 8);
};
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]
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]]);
Your browser information:
User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:59.0) Gecko/20100101 Firefox/59.0
.
Link to the challenge: