Tell us what’s happening:
Your code so far
As a non-native English speaker, I’ve been trying to understand both the logic and English about this challenge for few days.
This is the sample code from FCC
var denom = [
{ name: "ONE HUNDRED", val: 100 },
{ name: "TWENTY", val: 20 },
{ name: "TEN", val: 10 },
{ name: "FIVE", val: 5 },
{ name: "ONE", val: 1 },
{ name: "QUARTER", val: 0.25 },
{ name: "DIME", val: 0.1 },
{ name: "NICKEL", val: 0.05 },
{ name: "PENNY", val: 0.01 }
];
function checkCashRegister(price, cash, cid) {
var output = { status: null, change: [] };
var change = cash - price;
var register = cid.reduce(
function(acc, curr) {
acc.total += curr[1];
acc[curr[0]] = curr[1];
return acc;
},
{ total: 0 }
);
if (register.total === change) {
output.status = "CLOSED";
output.change = cid;
return output;
}
if (register.total < change) {
output.status = "INSUFFICIENT_FUNDS";
return output;
}
var change_arr = denom.reduce(function(acc, curr) {
var value = 0;
while (register[curr.name] > 0 && change >= curr.val) {
change -= curr.val;
register[curr.name] -= curr.val;
value += curr.val;
change = Math.round(change * 100) / 100;
}
if (value > 0) {
acc.push([curr.name, value]);
}
return acc;
}, []);
if (change_arr.length < 1 || change > 0) {
output.status = "INSUFFICIENT_FUNDS";
return output;
}
output.status = "OPEN";
output.change = change_arr;
return output;
}
Below is the part that I don’t really understand,
First, why do we need to use denom object???
Second, so the reduce function here started with an empty arry [ ]
at the very beginning
but what will register[curr.name]
be?? I tried to use console.log
to see but didn’t get anything.
Basically, I can’t figure out the following four lines…
(I guess it’s because I don’t know the usage of denom object)
If anyone can kindly explain this to me I would be very appreciated.
var change_arr = denom.reduce(function(acc, curr) {
var value = 0;
while (register[curr.name] > 0 && change >= curr.val) {
change -= curr.val;
register[curr.name] -= curr.val;
value += curr.val;
change = Math.round(change * 100) / 100;
}
if (value > 0) {
acc.push([curr.name, value]);
}
return acc;
}, []);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register