DJ Burb
DJ Burb

Reputation: 2364

Javascript refactoring. Dealing with repeat code

I have the following code:

  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;

Notice that most of the code is kind of repetitive accept for the setting of different properties in the object attachments. Is there anyway to get rid of the repetitive code? Or is it just what it is?

Upvotes: 0

Views: 37

Answers (1)

hair raisin
hair raisin

Reputation: 2628

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;

Update: slightly more succinct:

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

Upvotes: 2

Related Questions