[2,4,1,7,5].sort((a, b)=>a>b) // wrong
[2,4,1,7,5].sort((a, b)=>a-b) // correct
If I haven't used this function for several years, there will be a high possibility for me to use it in the wrong way.
Is there a technical means to avoid it?
[2,4,1,7,5].sort((a, b)=>a>b) // wrong
[2,4,1,7,5].sort((a, b)=>a-b) // correct
If I haven't used this function for several years, there will be a high possibility for me to use it in the wrong way.
Is there a technical means to avoid it?
If you think you're very likely to write code like your first example and you really want to avoid it, I can think of two ways:
Write a plugin for ESLint or similar that looks to see if the sort
callback returns the result of a comparison operation.
Write a development-time-only wrapper for sort
that throws an error if the callback doesn't return a number. But I probably wouldn't include it in the production version, just during development.
#2 looks something like this:
const sort = Array.prototype.sort;
Array.prototype.sort = function(callback) {
return sort.call(this, (a, b) => {
const rv = callback(a, b);
if (typeof rv !== "number") {
throw new Error("Array.prototype.sort callback must return a number");
}
return rv;
});
};
Live Example:
const sort = Array.prototype.sort;
Array.prototype.sort = function(callback) {
return sort.call(this, (a, b) => {
const rv = callback(a, b);
if (typeof rv !== "number") {
throw new Error("Array.prototype.sort callback must return a number");
}
return rv;
});
};
try {
console.log([2,4,1,7,5].sort((a, b)=>a>b));
} catch (e1) {
console.error(e1.message);
}
try {
console.log([2,4,1,7,5].sort((a, b)=>a-b));
} catch (e2) {
console.error(e2.message);
}