Skip to content

Instantly share code, notes, and snippets.

@berdfandrade
Created January 16, 2024 18:58
Show Gist options
  • Save berdfandrade/82be0aa504f3a07a308309d036e19881 to your computer and use it in GitHub Desktop.
Save berdfandrade/82be0aa504f3a07a308309d036e19881 to your computer and use it in GitHub Desktop.
function checkCashRegister(price, cash, cid) {
const valoresCorrentes = {
"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.1,
"QUARTER": 0.25,
"ONE": 1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDRED": 100
};
let trocoNecessario = cash - price;
let change = [];
// Calcule o total no caixa
let totalCID = 0;
for (let i = 0; i < cid.length; i++) {
totalCID += cid[i][1];
}
// Lidando com fundos insuficientes
if (totalCID < trocoNecessario) {
return { status: "INSUFFICIENT_FUNDS", change: [] };
}
// Caso o troco seja exato
if (totalCID === trocoNecessario) {
return { status: "CLOSED", change: cid };
}
// Fazendo o loop pelo cid
cid = cid.reverse();
for (let i = 0; i < cid.length; i++) {
let nomeDaMoeda = cid[i][0];
let moedaTotal = cid[i][1];
let valorCorrente = valoresCorrentes[nomeDaMoeda];
let moedaDisponivel = moedaTotal / valorCorrente;
let valorParaRetornar = 0;
// Percorrer a denominação do cid enquanto ainda houver troco desse tipo e troco ainda necessário.
while (trocoNecessario >= valorCorrente && moedaDisponivel > 0) {
trocoNecessario -= valorCorrente;
trocoNecessario = Math.round(trocoNecessario * 100) / 100;
moedaDisponivel--;
valorParaRetornar++;
}
// Adicionar a denominação ao array de troco se a moeda a ser devolvida for maior que 0.
if (valorParaRetornar > 0) {
change.push([nomeDaMoeda, valorParaRetornar * valorCorrente]);
}
}
// Lindando com o troco que sobrou
if (trocoNecessario > 0) {
return { status: "INSUFFICIENT_FUNDS", change: [] };
}
// Caso nenhuma condição seja satisfeita
return { status: "OPEN", change: change };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment