# Exact Change Code Review

Exact Change Code Review
0

#1

If anyone has the time, I’d be interested in comments on this solution to the Exact Change algorithm. I went with maps, here, but I’m not sure if that’s ideal.

``````var worthObj = {
"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.10,
"QUARTER": 0.25,
"ONE": 1.00,
"FIVE": 5.00,
"TEN": 10.00,
"TWENTY": 20.00,
"FIFTY": 50.00,
"HUNDRED": 100.00
};

function checkCashRegister(price, cash, cid) {
var change = cash - price;
var cidMap = new Map(cid.reverse());

// check for insufficient funds, etc.
var total = 0;
cidMap.forEach(function (value) {
total += value;
});
if (change > total ) {
return "Insufficient Funds";
} else if (change === total) {
return "Closed";
}

// bulk of the work.
cidMap.forEach(function (value,key,map) {
while (worthObj[key] <= change && value > 0 && change - worthObj[key] >= 0) {
value -= worthObj[key];
map.set(key, value);
change -= worthObj[key];
change = Math.round(change * 100) / 100;
}
});

// diff the map against the original cid.
var originalMap = new Map(cid.reverse());
var changeArr = [];
cidMap.forEach(function (value,key,map) {
if (map.get(key) != originalMap.get(key)) {
newValue = originalMap.get(key) - value;
newValue = Math.round(newValue * 100) / 100;
changeArr.push([key, newValue]);
}
});

// if change still needs to be accounted for,
// then we have insufficient funds.
// Otherwise, return array of change to be given
if (change > 0) {
return "Insufficient Funds";
} else {
return changeArr;
}
}

checkCashRegister(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]]); // should return [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15.00], ["ONE", 1.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]].
``````

Thanks!