Writing a generalized code

醉酒当歌 提交于 2020-01-06 20:01:47

问题


I have the following function where i hard code if conditions like 'AssignedTo','ClaimStatusId','ClaimTypeId'.

So, the strCondition string has any of the values like 'AssignedTo','ClaimStatusId','ClaimTypeId', then it will be redirected to corresponding if conditions

function ChangeIDToString(strCondition,id)
    {
        if (strCondition.indexOf("AssignedTo") > -1)
            return GetUserName(id)
        else if (strCondition.indexOf("ClaimStatusId") > -1)
            return GetClaimStatus(id)
        else if (strCondition.indexOf("ClaimTypeId") > -1)
            return GetClaimType(id);           
        else
            return id;
    }

Is there any way i can eliminate this hardcoded values like 'AssignedTo','ClaimStatusId','ClaimTypeId'?


回答1:


An approach like this?

function ChangeIDToString(strCondition,id)
    {
        return _func[strCondition]();
    }

var _func = {
   "AssignedTo":function(){ GetUserName(); },
   "ClaimStatusId":function(){ GetClaimStatus(); }
   ....
}



回答2:


You can try to use an object to store the string values, of course it is still hard coded because it is impossible that the machine understands that it need to execute "GetUserName()" when the condition is "AssignedTo".

var Conditions = {
    GetUserName: "AssignedTo",
    GetClaimStatus: "ClaimStatusId",
    GetClaimType: "ClaimTypeId"
}
function ChangeIDToString(strCondition,id)
{
    if (strCondition.indexOf(Conditions.GetUserName) > -1)
        return GetUserName(id)
    else if (strCondition.indexOf(Conditions.GetClaimStatus) > -1)
        return GetClaimStatus(id)
    else if (strCondition.indexOf(Conditions.GetClaimType) > -1)
        return GetClaimType(id);           
    else
        return id;
}


来源:https://stackoverflow.com/questions/34765426/writing-a-generalized-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!