javascriptsonarlint

Javascript SonarQube refactor this function to reduce its Cognitive Complexity


For below JavaScript function i am trying to figure out how to reduce the Cognitive Complexity.

function Person(data) {
    var self = this;
    if (data) {
        self.id = data.Id === null? "" : data.Id;
        self.name = data.Name === null? "" : data.Name;
        self.phone= data.Phone === null? "" : data.Phone;
        self.address = data.Address=== null ? "" : data.Address;
    } else {
        self.id = "";
        self.name = "";
        self.phone = "";
        self.address = "";
    }
}

Solution

  • Maybe something like this:

    function Person(data) {
        var self = this;
    
        self.id = "";
        self.name = "";
        self.phone = "";
        self.address = "";
    
        if (data) {
            self.id = getValueOrDefault(data.Id);
            self.name = getValueOrDefault(data.Name);
            self.phone = getValueOrDefault(data.Phone);
            self.address = getValueOrDefault(data.Address);
        }
    }
    
    function getValueOrDefault(value) {
        return value === null ? "" : value;
    }