Skip to content

Instantly share code, notes, and snippets.

@P1xt
Forked from anonymous/bonfire-exact-change.js
Created December 9, 2015 18:10
Show Gist options
  • Save P1xt/611ce5b7441c47709be2 to your computer and use it in GitHub Desktop.
Save P1xt/611ce5b7441c47709be2 to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/p1xt 's solution for Bonfire: Exact Change
// Bonfire: Exact Change
// Author: @p1xt
// Challenge: http://www.freecodecamp.com/challenges/bonfire-exact-change
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function drawer(price, cash, cid) {
var change = [];
var types = ['PENNY',
'NICKEL',
'DIME',
'QUARTER',
'ONE',
'FIVE',
'TEN',
'TWENTY',
'ONE HUNDRED'],
values = {
PENNY: 1,
NICKEL: 5,
DIME: 10,
QUARTER: 25,
ONE: 100,
FIVE: 500,
TEN: 1000,
TWENTY: 2000,
'ONE HUNDRED': 10000
},
cashback = Math.round((cash - price) * 100),
type = types.length - 1,
changeAmount = 0,
cashLeft = 0,
remainingchange, value, availableChange, drawnChange;
// while we still have cash in drawer
// and haven't given the full cashback due
// loop through the currency from largest denomination to smallest
while (type !== -1 && changeAmount !== cashback) {
remainingChange = cashback - changeAmount;
value = values[types[type]];
availableChange = Math.round(cid[type][1] * 100);
// we used up all this denomination, drop to smaller
if (value > remainingChange || availableChange === 0) {
type--;
cashLeft += availableChange;
// finished before denomination gone, push amount
} else {
drawnChange = Math.min(availableChange, remainingChange - remainingChange % value);
changeAmount += drawnChange;
cid[type][1] -= drawnChange / 100;
change.push([types[type], drawnChange / 100]);
}
}
if (changeAmount !== cashback) {
return 'Insufficient Funds';
} else if (cashLeft === 0) {
return 'Closed';
} else {
return change;
}
}
drawer(3.26, 100.00, [['PENNY', 1.01], ['NICKEL', 2.05], ['DIME', 3.10], ['QUARTER', 4.25], ['ONE', 90.00], ['FIVE', 55.00], ['TEN', 20.00], ['TWENTY', 60.00], ['ONE HUNDRED', 100.00]]);
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]
drawer(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment