This is my code:
const curencyUnits = [
["PENNY", 0.01],
["NICKEL", 0.05],
["DIME", 0.1],
["QUARTER", 0.25],
["DOLLAR", 1],
["FIVE", 5],
["TEN", 10],
["TWENTY", 20],
["HUNDRED", 100]
];
const result = {};
function giveChange(change) {
if (change <= 0) {
return change;
}
for (let i = 8; i > 0; i--){
let tmp = curencyUnits[i][1];
if (change % tmp === change){
continue;
}
if (change % tmp === 0) {
console.log("if === 0");
console.log(change % tmp);
console.log(change);
if (!(curencyUnits[i][0] in result)){
result[curencyUnits[i][0]] = 0;
}
result[curencyUnits[i][0]] += 1;
return change;
}
if (change % tmp <= tmp) {
console.log("if <= tmp");
console.log(change % tmp);
console.log(change);
if (!(curencyUnits[i][0] in result)){
result[curencyUnits[i][0]] = 0;
}
result[curencyUnits[i][0]] += 1;
giveChange(change - tmp)
}
}
}
giveChange(3.5);
The giveChange
function is supposed to calculate the type
and amount
of currency units the change
attribute has and include that in the result
object which is outside the function.
After the giveChange
function is called the result
object becomes { DOLLAR: 3, QUARTER: 4 }
. My question is: why am I getting 4 quarters instead of 2?