1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| function orderFilterTotal(order) { // 直接返回結果不需要再用一個變數來接 // 三元表達式(item.quantity ? item.quantity : 1) return order.items .reduce((total, item) => {return (item.price * (item.quantity || 1) + total) }, 0); }
if(orderFilterTotal({ items: [ {name:'cat food', price: 8, quantity: 2}, {name:'cat cage', price: 800, quantity: 3} ] }) != 2416) { throw new Error("Check Fail: Quantity Error)") }
if(orderFilterTotal({ items: [ {name:'cat food', price: 3} ] }) != 3) { throw new Error("Check Fail: No Quantity") }
if(orderFilterTotal({ items: [ {name:'cat food', price: 8}, {name:'cat cage', price: 800} ] }) != 808) { throw new Error("Check Fail: Happy Test(Example 1)") }
if(orderFilterTotal({ items: [ {name:'cat toy', price: 30}, {name:'cat towel', price: 40} ] }) != 70) { throw new Error("Check Fail: Happy Test(Example 2)") }
|