Hello there. I’ve recently finished JS Cash Register challenge and I think that I overcomplicated the code. What are the ways/tricks to simplify it? What are the patterns for simplification? Are there people that have/had the same problem?
My code is below:
let cidmap = [];
let temp = [];
let changeinitial = cash - price;
changeinitial = Number(changeinitial.toFixed(2));
let change = cash - price;
change = Number(change.toFixed(2));
let temp2 = [];
let allcash = cid.reduce((acc, currval) => acc + currval[1], 0);
allcash = Number(allcash.toFixed(2));
let open = {
status: "OPEN",
change: []
};
let insufficient = {
status: "INSUFFICIENT_FUNDS",
change: []
};
let closed = {
status: "CLOSED",
change: []
};
if (changeinitial > allcash) {
return insufficient;
} else if (changeinitial === allcash) {
closed.change = cid;
return closed; // new code
} else
cidmap = cid.map(function(cv) {
let obj = {};
switch (cv[0]) {
case 'PENNY':
cv[0] = 0.01;
break;
case 'NICKEL':
cv[0] = 0.05;
break;
case 'DIME':
cv[0] = 0.1;
break;
case 'QUARTER':
cv[0] = 0.25;
break;
case 'ONE':
cv[0] = 1;
break;
case 'FIVE':
cv[0] = 5;
break;
case 'TEN':
cv[0] = 10;
break;
case 'TWENTY':
cv[0] = 20;
break;
case 'ONE HUNDRED':
cv[0] = 100;
break;
}
obj[cv[0]] = cv[1];
return obj;
}).slice().reverse();
for (let i = 0; i < cidmap.length; i++) {
for (var key in cidmap[i]) {
if (cidmap[i].hasOwnProperty(key)) {
if (change >= Number(key)) {
//var x = Number(key);
if (cidmap[i][key] !== 0) {
temp.push(Number(key));
cidmap[i][key] = cidmap[i][key] - Number(key);
change = change - Number(key);
change = change.toFixed(2)
i = i - 1;
continue;
}
} else if (change === 0) {
break;
}
}
}
}
if (temp.reduce((a, b) => a + b) < change) {
return insufficient;
} else
temp.forEach(function(c, i) {
switch (c) {
case 0.01:
temp2.push(['PENNY', c]);
break;
case 0.05:
temp2.push(['NICKEL', c]);
break;
case 0.25:
temp2.push(['QUARTER', c]);
break;
case 0.1:
temp2.push(['DIME', c]);
break;
case 1:
temp2.push(['ONE', c]);
break;
case 5:
temp2.push(['FIVE', c]);
break;
case 10:
temp2.push(['TEN', c]);
break;
case 20:
temp2.push(['TWENTY', c]);
break;
case 100:
temp2.push(['ONE HUNDRED', c]);
break;
}
})
for (let a = 1; a < temp2.length; a++) {
if (temp2[a][0] === temp2[a - 1][0]) {
temp2[a][1] = temp2[a][1] + temp2[a - 1][1];
delete temp2[a - 1];
}
}
temp2 = temp2.filter((c) => c !== "");
open.change = temp2;
return open;
}
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]]);