Writing a generalized code

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'?

Answers:

Answer

An approach like this?

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

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

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;
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.