簡體   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