I’m at a loss as to how the Code Academy works at all. Depending on the engine, you could have just gotten lucky.
It’s not VS Code so much as the engine VS Code is using. My engine, node v18.13.0, also doesn’t sort with what you have. Let’s see why.
So:
const sortYears = (arr, fCmp) =>
arr.sort(fCmp);
const test = fCmp => {
const arr = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922];
console.log(fCmp.name);
console.log(JSON.stringify(arr));
console.log(JSON.stringify(sortYears(arr, fCmp)));
};
const cmp1 = (year1, year2) => year1 < year2 ? 1: 0;
test(cmp1);
Results:
cmp1
[1970,1999,1951,1982,1963,2011,2018,1922]
[1970,1999,1951,1982,1963,2011,2018,1922]
Perfect. Now, let’s watch:
const cmp2 = (year1, year2) => {
const result = year1 < year2 ? 1: 0;
console.log({ result, year1, year2});
return result;
};
Results:
cmp2
[1970,1999,1951,1982,1963,2011,2018,1922]
{ result: 0, year1: 1999, year2: 1970 }
{ result: 1, year1: 1951, year2: 1999 }
{ result: 0, year1: 1982, year2: 1951 }
{ result: 1, year1: 1963, year2: 1982 }
{ result: 0, year1: 2011, year2: 1963 }
{ result: 0, year1: 2018, year2: 2011 }
{ result: 1, year1: 1922, year2: 2018 }
[1970,1999,1951,1982,1963,2011,2018,1922]
Well, that was less than exciting. Let’s step back. You know that 0
means they match? If each time I get a 1
I needn’t swap, then no sorting is done.
Right, let’s fix it:
const cmp3 = (year1, year2) => {
const result = year1 - year2;
console.log({ result, year1, year2});
return result;
};
Results:
cmp3
[1970,1999,1951,1982,1963,2011,2018,1922]
{ result: 29, year1: 1999, year2: 1970 }
{ result: -48, year1: 1951, year2: 1999 }
{ result: -48, year1: 1951, year2: 1999 }
{ result: -19, year1: 1951, year2: 1970 }
{ result: 12, year1: 1982, year2: 1970 }
{ result: -17, year1: 1982, year2: 1999 }
{ result: -19, year1: 1963, year2: 1982 }
{ result: -7, year1: 1963, year2: 1970 }
{ result: 12, year1: 1963, year2: 1951 }
{ result: 41, year1: 2011, year2: 1970 }
{ result: 12, year1: 2011, year2: 1999 }
{ result: 36, year1: 2018, year2: 1982 }
{ result: 7, year1: 2018, year2: 2011 }
{ result: -60, year1: 1922, year2: 1982 }
{ result: -41, year1: 1922, year2: 1963 }
{ result: -29, year1: 1922, year2: 1951 }
[1922,1951,1963,1970,1982,1999,2011,2018]
Neat, a lot more hits on that one. Hmm, going the wrong way. The reverse is simple:
// we'll just return the value for this one
const cmp4 = (year1, year2) => year2 - year1;
Results:
cmp4
[1970,1999,1951,1982,1963,2011,2018,1922]
[2018,2011,1999,1982,1970,1963,1951,1922]
Now, if you must use that ternary you can write it like so:
const cmp5 = (year1, year2) => year1 < year2 ? 1 : -1;
Which, of course, is the answer. Thanks for reading. Hope something sparked some ideas.