Javascript重构。处理重复代码

时间:2015-07-15 15:45:31

标签: javascript refactoring

我有以下代码:

  switch(equipmentAttachment.AttachmentPosition)
  {
    case 'AttachFront':
    {
      if(equipmentAttachment.ProductCategoryDesc!='')
      {
        attachments.frontAttachment=equipmentAttachment.ProductCategoryDesc;
      }
      else
      {
        attachments.frontAttachment=equipmentAttachment.ProductCategoryName;
      }
      break;
    }
    case 'AttachRear':
    {
      if(equipmentAttachment.ProductCategoryDesc!='')
      {
        attachments.backAttachment=equipmentAttachment.ProductCategoryDesc;
      }
      else
      {
        attachments.backAttachment=equipmentAttachment.ProductCategoryName;
      }  
      break;        
    }
    case 'Tertiary':
    {
      if(equipmentAttachment.ProductCategoryDesc!='')
      {
        attachments.thirdAttachment=equipmentAttachment.ProductCategoryDesc;
      }
      else
      {
        attachments.thirdAttachment=equipmentAttachment.ProductCategoryName;
      }
      break;
    }
  }
  return attachments;

请注意,大多数代码都是对对象attachments中不同属性的设置进行重复接受。反正有没有摆脱重复的代码?或者它就是它的本质?

1 个答案:

答案 0 :(得分:2)

var posMap = {
  "AttachFront": "frontAttachment", 
  "AttachRear": "backAttachment", 
  "Tertiary": "thirdAttachment"
};
if(posMap[equipmentAttach.AttachmentPosition])
{
  var target = posMap[equipmentAttach.AttachmentPosition];
  attachments[target] = (equipmentAttachment.ProductCategoryDesc || equipmentAttachment.ProductCategoryName);
}
return attachments;

更新:稍微简洁:

var target = {
  "AttachFront": "frontAttachment", 
  "AttachRear": "backAttachment", 
  "Tertiary": "thirdAttachment"
}[equipmentAttach.AttachmentPosition];
if(target)
{
  attachments[target] = (equipmentAttachment.ProductCategoryDesc || equipmentAttachment.ProductCategoryName);
}
return attachments;