0

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?

1 Answer 1

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;

Update: slightly more succinct:

var target = {
  "AttachFront": "frontAttachment", 
  "AttachRear": "backAttachment", 
  "Tertiary": "thirdAttachment"
}[equipmentAttach.AttachmentPosition];
if(target)
{
  attachments[target] = (equipmentAttachment.ProductCategoryDesc || equipmentAttachment.ProductCategoryName);
}
return attachments;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.