繁体   English   中英

Javascript - 概括两个相似的功能

[英]Javascript - Generalizing two similar functions

我有两种类似的方法:

function getFeedPizzasMinimumDate(startDate, totalPizzas) {
  // 2 weeks if there are less than 10 pizzas
  let numberOfDaysToDecrase = 14;

  // 3 days if there are more than 1k pizzas
  if (totalPizzas >= 1000) numberOfDaysToDecrase = 3;

  // 5 days if there are from 100 to 1k pizzas
  else if (totalPizzas >= 100) numberOfDaysToDecrase = 5;

  // 1 week if there are from 10 to 100 pizzas
  else if (totalPizzas >= 10) numberOfDaysToDecrase = 7;

  return substractDaysToDate(numberOfDaysToDecrase, startDate);
}

和:

function getFeedSpaghettisMinimumDate(startDate, totalSpaghettis) {
  // 3 weeks if there are less than 10 spaghettis
  let numberOfDaysToDecrase = 21;
    
  // 5 days if there are more than 1k spaghettis
  if (totalSpaghettis >= 1000) numberOfDaysToDecrase = 5;
    
  // 1 week if there are from 100 to 1k spaghettis
  else if (totalSpaghettis >= 100) numberOfDaysToDecrase = 7;
    
  // 2 weeks if there are from 10 to 100 pizzas
  else if (totalSpaghettis >= 10) numberOfDaysToDecrase = 14;
    
  return substractDaysToDate(numberOfDaysToDecrase, startDate);
}

如您所见,两种方法的代码非常相似,只是数字不同。

假设“启发式”计算的数字(通过假设,没有任何公式)。

我可以使用哪种模式将这两种方法概括为一个“getFeedPlatesMinimumDate”? 当代码原子性很高时,我应该避免泛化代码吗?

我会为披萨做这样的事情。 通过将 if 语句中的值更改为类型 === 'spaghettis' 对意大利面条执行相同的操作。 如果你使用的是 typescript,你也可以直接注入 type 值可以有什么样的类型。 否则,也可以选择使用 ENUMS。

function getFeedMinimumDate(startDate, amount, type = 'pizza') {
  // default
  let numberOfDaysToDecrase = 14;

  // 3 days if there are more than 1k pizzas
  if (type === 'pizza' && amount >= 1000) numberOfDaysToDecrase = 3;

  // 5 days if there are from 100 to 1k pizzas
  if (type === 'pizza' && amount >= 100) numberOfDaysToDecrase = 5;

  // 1 week if there are from 10 to 100 pizzas
  if (type === 'pizza' && amount >= 10) numberOfDaysToDecrase = 7;

  return substractDaysToDate(numberOfDaysToDecrase, startDate);
}

您可以只传递一个名为 data 的 json 对象,其中包含您想要的数字,或者使用 switch 语句或 if 语句用于 json 对象的数据已经存在

第一个选项

const data = {
  Pizza:10,
  Slices:20
}
function allFood(data){
  return data.Pizza*data.Slices
}

选项二

function allFood(Food){
//use switch statement or if statement
 const PData={amount:10,fed:10};  //pizza data
 const SData={amount:5,fed:15}; //spaghetti data
 if (Food ==='Pizza'){
  return PizzaData.amount*PizzaData.fed;
 }else if(Food ==='Spaghetti'){
  return SpaghettiData.amount*SpaghettiData.fed;
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM