Define this function outside of a loop

javascript sonarqube

537 观看

1回复

1173 作者的声誉

I have the following code :

for (var entry in metadata) {
     if (metadata.hasOwnProperty(entry)) {
         var varName = metadata[entry].variableName;
         if (metadata[entry].multipleValues === "false") {
             if (angular.isDefined(vm[varName]) && (vm[varName] !== null) && vm[varName].id !== null) {
                 filters.push(factory.buildEntry(metadata[entry].variableName, vm[varName].id, null, factory.filterOperators.textContains));
             }
         } else {
             if (angular.isDefined(vm[varName]) && (angular.isArray(vm[varName])) && (vm[varName].length > 0)) {
                 filters.push(factory.buildEntry(metadata[entry].variableName, null, vm[varName].map(function (item) {
                     return item.id;
                 }), factory.filterOperators.textContains));
             }
         }
     }
}

But SonarQube keeps telling me to Define this function outside of a loop., and the only function I have inside this loop is the anonymous function I pass to the Array.prototype.map() method :

function (item) {
    return item.id;
}

Which would be useless if I define it outside my loop since it's body only contains one line of code.

Why I'm getting this error ? and how can I tell SonarQube to skip it.

作者: Ichigo Kurosaki 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

18016 作者的声誉

How about you define it outside the loop

var mapFunction = function (item) {
                     return item.id;
                 };
for (var entry in metadata) {
     if (metadata.hasOwnProperty(entry)) {
         var varName = metadata[entry].variableName;
         if (metadata[entry].multipleValues === "false") {
             if (angular.isDefined(vm[varName]) && (vm[varName] !== null) && vm[varName].id !== null) {
                 filters.push(factory.buildEntry(metadata[entry].variableName, vm[varName].id, null, factory.filterOperators.textContains));
             }
         } else {
             if (angular.isDefined(vm[varName]) && (angular.isArray(vm[varName])) && (vm[varName].length > 0)) {
                 filters.push(factory.buildEntry(metadata[entry].variableName, null, vm[varName].map(mapFunction), factory.filterOperators.textContains));
             }
         }
     }
}

You can assign functions to variables and then treat that variable as a function

var foo = function(){console.log('bar')};
foo();

In your case by assigning your mapping function to a variable, then passing that variable to the .map() gives you also an efficiency boost, because the function doesn't have to be re-instantiated every single time the loop runs. It can just re-use the same function over and over.

And as soon as the enclosing function ends which executes the loop, the variable ceases to exist.

作者: Tschallacka 发布者: 2017 年 12 月 27 日
32x32