Upon inheriting a codebase, also known as "legacy code," I have been extremely cautious not to make any unintended changes. While attempting to auto-format the code, I encountered an error.
The function in question is meant to sort a chart. There is a part of the code that appears confusing to me:
function sortChartBy(field,dir=1) {
if(g_sortMethod != field){
g_sortDir = 1;
}
g_sortMethod = field;
g_sortDir = g_sortDir * -1 * dir;
var ranks = g_chart["ranks"];
var sortMethod = g_sortMethod;
var sortDir = g_sortDir;
var sortFunc = undefined;
if(field == "release_date"){
sortFunc = function(a,b){
var aVal = a[sortMethod];
var bVal = b[sortMethod];
if(aVal == "1970-01-01") aVal = "9999--99-99";
if(bVal == "1970-01-01") bVal = "9999-99-99";
if(aVal < bVal) return -1 * sortDir;
if(aVal > bVal) return 1 * sortDir;
return 0;
};
}else{
sortFunc = function(a,b){
var aVal = a[sortMethod];
var bVal = b[sortMethod];
// ###### QUESTION HERE ########################################
if (aVal == -1 && bVal !=- -1) return 1;
// 'bVal !=- -1' What does that mean? Why '-' directly after '!='
if (aVal != -1 && bVal == -1) return -1;
if (aVal < bVal) return -1 * sortDir;
if (aVal > bVal) return 1 * sortDir;
return 0;
};
}
ranks.sort(sortFunc);
renderChart();
}
Utilizing IntelliJ as my IDE, I noticed that during auto-formatting, the '-' character following '!=' moves one position to the right in the line:
if (aVal == -1 && bVal != --1) return 1; // Invalid left hand side in prefix expression
IntelliJ displays an error indicating
Invalid left hand side in prefix expression
and marks the '1' with a red underline as erroneous.
I am puzzled by the presence of two minuses separated by a space !=- -1
in the original code and why this would trigger an error upon autoformatting. Although the code functions correctly in its original form, I haven't encountered !=-
syntax in JavaScript before, which raises doubts about its validity.
I am seeking clarification on why the line
if (aVal == -1 && bVal !=- -1) return 1;
executes without issue initially but throws an error post autoformatting.
How should the correct code be structured?