Last active
August 3, 2016 02:09
-
-
Save zhangolve/40a244aee8198a4e949bdfecc3b77d47 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create an object which hold the denominations and their values 建立一个json来将原来的英文表述转化为数字表述,方便以后的比较 | |
var denom = [ | |
{ name: 'ONE HUNDRED', val: 100.00}, | |
{ name: 'TWENTY', val: 20.00}, | |
{ name: 'TEN', val: 10.00}, | |
{ name: 'FIVE', val: 5.00}, | |
{ name: 'ONE', val: 1.00}, | |
{ name: 'QUARTER', val: 0.25}, | |
{ name: 'DIME', val: 0.10}, | |
{ name: 'NICKEL', val: 0.05}, | |
{ name: 'PENNY', val: 0.01} | |
]; | |
function checkCashRegister(price, cash, cid) { | |
var change = cash - price;//找零数额等于给的现金数目减去商品价格 | |
// Transform CID array into drawer object reduce方法是累加器,用于累加,这里就是计算抽屉里的总金额数 | |
//arr.reduce(callback,[initialValue]) 第二个参数是累加器的初始值,在这里初始值是total:0 | |
var register = cid.reduce(function(acc, curr) { | |
acc.total += curr[1]; | |
acc[curr[0]] = curr[1]; | |
return acc; | |
}, {total: 0}); | |
// Handle exact change 抽屉里的金额与需找零相等 | |
if (register.total === change) { | |
return 'Closed'; | |
} | |
// Handle obvious insufficent funds 抽屉里的金额不足 | |
if (register.total < change) { | |
return 'Insufficient Funds'; | |
} | |
// Loop through the denomination array 遍历开头创建的数组, | |
var change_arr = denom.reduce(function(acc, curr) { | |
var value = 0; | |
// While there is still money of this type in the drawer | |
// And while the denomination is larger than the change reminaing有这种类型的钱,并且这种类型的钱比需找要少。 | |
//比如需找30,20元面值的钱有1张,这就够了。 | |
//这里的 curr.name | |
while (register[curr.name] > 0 && change >= curr.val) { //这就是上面提到的30元比20元多的情况 | |
change -= curr.val; //重新设定需找数额,这时候就是还差10元了,因为已经有1张20元 | |
register[curr.name] -= curr.val; //拿总金额数来减 | |
value += curr.val; | |
// Round change to the nearest hundreth deals with precision errors | |
change = Math.round(change * 100) / 100; | |
} | |
// Add this denomination to the output only if any was used. | |
if (value > 0) { | |
acc.push([ curr.name, value ]); | |
} | |
return acc; // Return the current Change Array | |
}, []); // Initial value of empty array for reduce | |
// If there are no elements in change_arr or we have leftover change, return | |
// the string "Insufficient Funds" | |
if (change_arr.length < 1 || change > 0) { | |
return "Insufficient Funds"; | |
} | |
// Here is your change, ma'am. | |
return change_arr; | |
} | |
// test here | |
checkCashRegister(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