I have found an oddity when using Array.prototype.sort() on an array of numbers and I'm not sure what's causing it.
My goal is to reverse an array using sort (not using reverse) so I can chain it like so:
const shouldReverse = Math.random() > 0.5,
result = foo().bar().map(...).reverseIf(shouldReverse);
I believe I should be able to achieve this using sort, which seems to work in some cases but not others.
Here is a working example:
const myArray = ['a', 'b', 'c', 'd'],
mySortedArray = myArray.sort(() => 1);
console.log(mySortedArray);
["d", "c", "b", "a"]
And a non-working example:
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'],
mySortedArray = myArray.sort(() => 1);
console.log(mySortedArray);
["f", "k", "a", "j", "i", "h", "g", "b", "e", "d", "c"]
This only happens in Chrome and only when there are more than 10 elements in the array — could it be some form of optimisation in Chrome's V8 engine?
sort, then you would need sorting functions first but then you can very simply make them work the opposite way by doing areverse = x => () => x * -1of if you want to be more fancyreverse = (f) => function () { return f.apply(this, arguments) * -1; }