HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

A more efficient way to make JQL (Jira Query Language)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
jqljiraquerymorewaymakeefficientlanguage

Problem

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.

Solution

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.

Code Snippets

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

// Try something like this 
makeJQL({
    status: "status",
    project: "project",
    priority: "priority"
});
makeJQL: function(jqlObject){
    var arr = new Array();
    Object.keys(jqlObject).forEach(function(key) {
          array.push(key + "="+'"'+ jqlObject[key] +'"');
    });
}

Context

StackExchange Code Review Q#141792, answer score: 3

Revisions (0)

No revisions yet.