gpt4 book ai didi

JavaScript 重构。处理重复代码

转载 作者:行者123 更新时间:2023-12-02 15:57:58 27 4
gpt4 key购买 nike

我有以下代码:

  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 中不同属性的设置。有没有办法去掉重复的代码?或者它就是这样?

最佳答案

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;

关于JavaScript 重构。处理重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31435083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com