I think there are 2 tests that have conflicting assertions. Like the following test (the 3rd)
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]]}
which to my understanding, the test reads given the cid
containing all the currency units, the function should return the change
with array of non-zero currency unit. As you can see, there’s no ["ONE HUNDRED", 0]
.
Where as this test (the last one),
checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
should return {status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}
the function is expected to return the change
with all the currency units.
The issue I have is when I fixed the first one test, it breaks the other and vice versa. Therefore, the questions are:
- How do you combine these 2 tests into a better description on what is expected value of
change
to return? - What are each tests are trying to prove?
So with better description I can refactor my function accordingly.
Here’s the code I have so far.
function checkCashRegister(price, cash, cid) {
var changeAmount = cash - price;
const unitDef = {
'ONE HUNDRED': 100,
TWENTY: 20,
TEN: 10,
FIVE: 5,
ONE: 1,
QUARTER: 0.25,
DIME: 0.1,
NICKEL: 0.05,
PENNY: 0.01
};
var changes = [];
Object
.keys(unitDef)
.forEach((unit) => {
let totalUnitChange = 0
let cidPair = cid.find(([unitName, _totalUnit]) => unitName == unit);
let availableUnit = cidPair[1]
if (changeAmount < unitDef[unit]) {
if (availableUnit == 0) {
changes.push([unit, 0])
}
return;
}
while (changeAmount >= unitDef[unit] && totalUnitChange < availableUnit) {
changeAmount = parseFloat((changeAmount - unitDef[unit]).toFixed(2));
totalUnitChange = parseFloat((totalUnitChange + unitDef[unit]).toFixed(2));
}
changes.push([unit, totalUnitChange]);
if (totalUnitChange > 0) {
cidPair[1] -= totalUnitChange
}
});
if (changeAmount > 0) {
return {
status: 'INSUFFICIENT_FUNDS',
change: []
};
}
var result = {}
if (changes.length > 0) {
if (cid.every(([_unitName, totalUnit]) => totalUnit === 0)) {
result.status = 'CLOSED';
} else {
result.status = 'OPEN';
}
result.change = changes
}
return result;
}
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 x86_64; rv:90.0) Gecko/20100101 Firefox/90.0
Challenge: Cash Register
Link to the challenge: