4
\$\begingroup\$

So my code here takes some parameters and then creates an SQLesque type of string (JQL).

function makeJQL(status, project, priority, description, summary){
    var arr = new Array();
    // Could put a null check here if all parametres are undefined
        if(status.length > 0){
            jql = "status="+'"'+status+'"';
            arr.push(jql)
        }
        if(project.length > 0){
            jql = "project="+'"'+project+'"';
            arr.push(jql)
        }
        if(priority.length > 0){
            jql = "priority="+'"'+priority+'"';
            arr.push(jql)
        }
        if(description.length > 0){
            jql = "description="+'"'+description+'"';
            arr.push(jql)
        }
        if(summary.length > 0){
            jql = "summary="+'"'+ summary +'"';
            arr.push(jql)
        }
        var jql = "";
        for(var i = 0; i < arr.length; i++){
            jql = jql + arr[i]+ ' AND '
        }
        jql = jql.substring(0, jql.length - 5);
        return jql
}

The only thing is, is that there is a lot of code repetition, but I don't know how to overcome this really. I also haven't put a null check in because if the function is called, there has to be parameters passed.

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Instead of passing parameters to this function you can pass a single object and iterate through it.

// instead of this
makeJQL("status", "project", "priority", "description", "summary");

// Try something like this 
makeJQL({
    status: "status",
    project: "project",
    priority: "priority"
});

And to itinerate the object passed to the function you can use Object.keys():

makeJQL: function(jqlObject){
    var arr = new Array();
    Object.keys(jqlObject).forEach(function(key) {
          array.push(key + "="+'"'+ jqlObject[key] +'"');
    });
}

Other good practice would be implement a function for each request in your application, creating a makeSomethingJQL will increase the readability of your code.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.