Issue
Please if this function was to be converted to a "normal" if else statement, how would it look like?
export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));
I want to add another condition, but I'm finding it hard to read or digest the current flow.
Solution
First lets expand the code to make it (slightly) easier to read.
Note that the ?:
contains questionable logic, use of ===
seems to suggest it is trying to handle sorting an array of mixed types, but then using non-strict <
and >
comparisons. So for the purposes of the rest of this answer I am going to assume it is not trying to sort mixed typed arrays or that if it is, it will ignore strict type comparisons (ie the ===
should really be ==
)
function orderArr (arr: any[], key: string) {
function sorter(a, b) {
return (
(a[key] > b[key])
? 1
: (a[key] === b[key])
? (
(a[key] > b[key])
? 1
: -1
)
: -1
);
}
return arr.sort(sorter);
}
export orderArr;
Now lets re-write the overcomplicated ?:
expression (overcomplicated not because of the ?:
syntax but because its doing more than it needs to) and rewrite as if then elses (note, this code is still wrong)
function sorter(a, b) {
if (a[key] > b[key]) {
return 1; // return 1 if a > b
} else {
if (a[key] === b[key]) { // questionable logic
if (a[key] > b[key]) { // questionable logic
return 1;
} else {
return -1; // will always return -1 (wrong, a == b should return 0)
}
} else {
return -1; // return -1 if a < b
// or if type of a does not equal type of b (questionable)
}
}
}
Now lets simplify and fix the bug (ie remove the strict type comparison). Using a technique called early return (also called guard clauses), and avoiding using else as it adds unnecessary indentation and complication
function sorter(a, b) {
if (a[key] > b[key]) return 1;
if (a[key] < b[key]) return -1;
return 0;
}
Or if you prefer, using ?:
syntax
function sorter(a, b) {
return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
}
If you are sorting numbers, you can use a little trick to further simplify the code. Sort expects a 0
if a
and b
are equal, a negative value if a < b
and a positive value if a > b
, so for numeric sorting we can simply do
function sorter(a, b) {
return a[key] - b[key];
}
Now, lets put all the simplified code back together into a single line. First for any type of array.
export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);
and for a numerical only array
export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] - b[key]);
Answered By - Austin France
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.