S3003 flagging where lexicographic sort is intended

Using SonarCloud, analysing code like:

        result = result.sort((x, y) => x.code > y.code ? +1 : -1);

Flags with S3003, when trying to sort an array lexicographically by a property of the objects within it - the rule description suggests it is (only) supposed to pick up cases like:

var appleNumber = "123";
var orangeNumber = "45";
if (apple < orange) {  // Noncompliant, this condition is true
  alert("There are more oranges");

Rather than:

var apple = "apple";
var orange = "orange";
if (apple < orange) {  
  alert("'apple' does come before 'orange' in the dictionary");

Perhaps a better version of this rule would be the type differs on either side of the operator (e.g. "123" < 45 as JavaScript/TypeScript let you do stupid things like that; or where at least one side is known to be a constant string that looks like a number e.g. let dumb = "123"; // Flag this! (in TypeScript)

Hello @RowlandShaw,

Sorry for answering this late.

The scope of the rule is not limited to the example of the rule description, i.e. only comparisons in the condition of if statements. Since comparisons are binary expressions, they can appear (almost) anywhere in the code.

Coming back to the point you are raising, it would indeed make sense to add an exception to the rule for the particular case of lexicographic sort. I created a ticket to address this issue as soon as possible.

Thank you for reporting us this false positive.


1 Like