了解FreeCodeCamp Exact Change挑战解决方案(re:reduce方法)

时间:2018-01-15 18:44:59

标签: javascript algorithm reduce

我参加了Exact Change挑战赛。我需要创建一个函数:

  1. 接受购买价格作为第一个arg(价格),付款作为第二个艺术品(现金),现金抽屉arg( cid < / EM>)

  2. cid 是2D arr,列出可用货币

  3. 返回&#34;资金不足&#34;,如果 cid 小于变更到期,并返回&#34;已关闭&#34;如果 cid 等于更改到期

  4. 否则,返回硬币和账单的变化,按从高到低的顺序排序

  5. checkCashRegister(19.50,20.00,[[&#34; PENNY&#34;,1.01],[&#34; NICKEL&#34;,2.05],[&#34; DIME&#34;,3.10 ],[&#34; QUARTER&#34;,4.25],[&#34; ONE&#34;,90.00],[&#34; FIVE&#34;,55.00],[&#34; TEN&#34; ,20.00],[&#34; TWENTY&#34;,60.00],[&#34; ONE HUNDRED&#34;,100.00]])应该返回[[&#34; QUARTER&#34;,0.50]]

  6. 我在论坛上找到了这个解决方案,因为它很干净,并且显示用reduce()创建一个对象数组 - 但是理解第二个reduce()有点令人困惑函数中的方法。以下是代码:

    &#13;
    &#13;
    const 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} 
    ] //a template object 
    
    function checkCashRegister(price, cash, cid){
    	let change = cash - price
    
    	const register = cid.reduce(function(acc, curr){
    		acc.total += curr[1]
    		acc[curr[0]] = curr[1]
    		return acc
    	}, {total: 0}) //creating register object with reduce()
    
    	if(register.total === change){
    		return 'Closed'
    	} //handle exact change
    
    	if(register.total < change){
    		return 'Insufficient Funds'
    	} //return insufficient change
    
    	let change_arr = denom.reduce(function(acc, curr){
    		let value = 0 //while there is still money of this type in the drawer
    					//and while the denom is larger than the change remaining
    		while(register[curr.name] > 0 && change >= curr.val){
    			change -= curr.val
    			register[curr.name] -= curr.val
    			value += curr.val
    			change = Math.round(change*100)/100
    		}
    
    		if(value > 0){
    			acc.push([curr.name, value])
    		}
    		return acc;
    	}, [])
    
    	if(change_arr.length<1 || change >0){
    		return 'Insufficient Funds'
    	}
    
    	return change_arr
    }
    
    
    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]]);
    &#13;
    &#13;
    &#13;

    我的问题是,看起来这段代码看起来没有用于处理我们通过 cid 参数收到的数据。我非常确定我遗漏了一些关于使用模板数组(const denom)和/或将cid参数转换为对象和/或数组的问题。

    有人能解释一下第二个reduce方法(让change_arr = denom.reduce())在函数中发生了什么吗?

    编辑:我认为它没有处理 cid 参数以及寄存器对象

0 个答案:

没有答案