优化以避免在程序中重复自己

时间:2016-11-16 11:01:08

标签: javascript

我在下面写了这个非常简单的比萨订单程序,但我觉得我在部分重复自己。任何优化提示?

代码:



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);




2 个答案:

答案 0 :(得分:4)

这是一个很好的小程序,你已经到了那里。

为什么不考虑通过Pizza构造函数学习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');

答案 1 :(得分:-1)

由于您的orderCount是全局的,因此您无需在函数getSubTotal中传递它。另外,将getSubTotal()值保存在变量中。无需一次又一次地调用它。