要求
设计一个收银程序 checkCashRegister() ,其把购买价格(price)作为第一个参数 , 付款金额 (cash)作为第二个参数, 和收银机中零钱 (cid) 作为第三个参数.
cid 是一个二维数组,存着当前可用的找零.
当收银机中的钱不够找零时返回字符串 "Insufficient Funds". 如果正好则返回字符串 "Closed".否则, 返回应找回的零钱列表,且由大到小存在二维数组中.
解答
function checkCashRegister(price, cash, cid) {
var change;
var base=100;
change=(cash-price)*base;
var getTotalMoney=function(arr){
var s=arr.reduce(function(preV,currV,currIndex,array){
return preV+currV[1];
},0);
return s*base;
};
var objCash={
"PENNY": 1,
"NICKEL": 5,
"DIME": 10,
"QUARTER": 25,
"ONE": 100,
"FIVE": 500,
"TEN": 1000,
"TWENTY": 2000,
"ONE HUNDRED": 10000
};
var totalMoney=getTotalMoney(cid);
if(totalMoney<change)
return "Insufficient Funds";
var changearr=[];//找钱列表
var currMoney=0;//当前面额
var currLast=0;//当前面值所剩余额
var currTotal=0;//当前零钱可找总额
for(i=cid.length-1;i>=0;i--){
currMoney=objCash[cid[i][0]];
currLast=cid[i][1]*base;
if(currLast===0) continue;
if(change>currMoney){
if(change<currLast)
currTotal=currMoney*Math.floor(change/currMoney);
else
currTotal=currLast;
change-=currTotal;
changearr.push([cid[i][0],currTotal/base]);
}
}
if(change>0)//找不开
return "Insufficient Funds";
else if((change===0)&&((cash-price)*base==totalMoney))
return "Closed";
else
return changearr;
}
// 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]]
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]]);