Skip to content Skip to sidebar Skip to footer

How To Generalize A Function?

I am using the below function, I am trying to generalize the function without using hardcoded values. How i can achieve it? function ChangeIDToString(strCondition,id) {

Solution 1:

It would be nice to see what your functions do.

But in your functions, you can declare:

var j={"id":"return of your function string here"};
JSON.stringify(j); // '{"id":"return of your function string here"}'

Solution 2:

You could create an object of functions, and then call a function named by strCondition using bracket notation and dynamic property name. Something like this:

var objOfFunctions = {
    GetUserName: function (id) {...},
    GetClaimStatus: function (id) {...},
    GetClaimType: function (id) {...}
};

function ChangeIDToString(strCondition,id) {
    if (!objOfFunctions.hasOwnProperty(strCondition)) {
        return id;
    }
    return objOfFunctions[strCondition](id);
}

In a case you already have a lot of calls to the functions in objOfFunctios somewhere else in your code, you can populate that object with references too.

A live demo using references in objOfFunctions at jsFiddle.


EDIT

After discovered that you've asked this same question before, it looks like my original answer still hardcodes too much. (Your comment to void's similar answer.)

The goal can still be achieved by passing a function reference instead of a string to ChangeIDToString. Though you will lose the ability to check, which function will be called. Like this:

function ChangeIDToString(refCondition,id) {
    if (typeof refCondition !== 'function') {
        return id;
    }
    return refCondition(id);
}
// Invoke example
console.log(ChangeIDToString(GetClaimType, 'some_ID'));

A demo at jsFiddle.

If the string can't be replaced with a reference, your last resort is to use eval(), but it's strongly recommended not to do so.

An eval demo at jsFiddle.


Solution 3:

You weren't clear as to where/how you wanted JSON to fit into your solution, but if you are saying that there will definitely be one of those 3 strings passed into the function and which function gets called from there is based on which string is passed in, then you could leverage the fact that all arguments are optional in JavaScript. As long as your function only gets called with 2 arguments (id and one of the others), this would do it:

function ChangeIDToString(id, user, claimStatusId, claimTypeId)
{
   if (user !== null)
       return GetUserName(id)
   else if (claimStatusId !== null)
       return GetClaimStatus(id)
   else if (claimTypeId !== null)
       return GetClaimType(id);           
   else
       return id;
}

https://jsfiddle.net/m271cpum/ for more complete example.


Post a Comment for "How To Generalize A Function?"