Almost any time I need to reverse an array, it's a conditional operation, which leads me to do something like this:
const arr = [1, 2, 3];
let sortReversed = true; // reactive variable
const processedArr = sortReversed ? arr.slice().reverse() : arr;
// ...or...
const processedArr = sortReversed ? arr.toReversed() : arr;
It would be great to be able to simply pass in the reactive variable, so I can do something like this:
const processedArr = arr.slice().reverse(sortReversed);
// ...or...
const processedArr = arr.toReversed(sortReversed);
This is especially useful when I need to conditionally swap destructure two variables from a tuple-style array that is conditionally reversed. Here is my present IRL example:
let [organization, individual] = [provider, focalProvider];
if (focalEntityType === EntityTypeCode.Organization) {
[organization, individual] = [individual, organization];
}
If I want to declare these array objects with const
, it would looks more like this:
const [organization, individual] = focalEntityType === EntityTypeCode.Organization
? [focalProvider, provider]
: [provider, focalProvider];
With an argument supplied to reverse
and toReversed
, we could achieve the same much simpler like this:
const [organization, individual] = [provider, focalProvider].slice().reverse(focalEntityType === EntityTypeCode.Organization);
// ...or...
const [organization, individual] = [provider, focalProvider].toReversed(focalEntityType === EntityTypeCode.Organization);