2016-11-16 66 views
0

我寫了這個真正簡單的比薩訂單程序下面,但我覺得我重複自己的部分。任何優化技巧?優化,以避免重複自己在程序中

代碼:

var orderCount = 0; 
 

 
function takeOrder(crustType, topping) { 
 
    console.log('Order:' + crustType + ' ' + 'pizza' + ' ' + topping); 
 
    orderCount = orderCount + 1; 
 
} 
 

 
function getSubTotal(itemCount) { 
 
    return itemCount * 7.5; 
 
} 
 

 
function calculateVat(VAT) { 
 
    return VAT/10 * 2; 
 
} 
 

 
// List the orders 
 
takeOrder('Thin Crust Pizza', 'with bacon'); 
 
takeOrder('Fat Crust Pizza', 'with pepporoni'); 
 
takeOrder('Medium Crust Pizza', 'with Vegi'); 
 
takeOrder('Medium Crust Pizza', 'with steak'); 
 
takeOrder('Medium Crust Pizza', 'with Sausage'); 
 
// List the Total Minus VAT 
 
console.log(getSubTotal(orderCount)); 
 

 
//Stores the cost with and With out VAT 
 
var totalNoVAT = getSubTotal(orderCount); 
 
var totalYesVAT = getSubTotal(orderCount) + calculateVat(totalNoVAT); 
 

 
//Log the cost of the VAT and Total Order Cost with VAT 
 
console.log('The VAT on that order would be' + ' ' + calculateVat(totalNoVAT)); 
 
console.log('This give you a grand total of' + ' ' + totalYesVAT);

+1

使用類似這樣的函數實際上並不覺得重複 - 你做得很好!儘管如此,您可能希望將''從'topping'字符串移到'takeOrder'函數中。不要反覆調用該函數,您可能需要使用一組指令並對其進行迭代。 – Bergi

+0

@vlaz重複,我猜OP意味着他必須多次調用一個函數。他可以刪除,如果他接受PARAMS作爲數組對象 – Rajesh

+0

嗨Rajesh,謝謝你的回答是更多隻是意見/建議,道歉會確保我放在那裏下一次 – kiannjie101

回答

-1

因爲你的定單計數是全局的,你不需要它傳遞函數getSubTotal。另外,將getSubTotal()值保存在變量中。無需一次又一次地調用它。

4

這是一個整潔的小程序,你有。

爲什麼你不考慮通過比薩構造函數學習JavaScript構造函數?

function order(size, topping, price, customer, address) { 
    this.Pizza = { 
     Size: size; 
     Toppings: toppings; 
    }, 
    this.Price = price; 
    this.Customer = customer; 
    this.DeliveryAddress = address; 
} 

var order_one = new order ('12"', 'Pepperoni', 12.99, 'Josh', '1, Typical Street, Typicaltown');