Best way to do conditional array methods in javascript

Viewed 2200

Assume we have function that returns array let's say fn(parm1, parm2, parm3) and i want to conditional reverse the returned array.

I know you can do something like this:

condition ? fn(parm1, parm2, parm3).reverse() : fn(parm1, parm2, parm3)

But in my case I don't want to call it twice. Not the array or even the function that calls the array.

So my question, is there something obvious to do and I've missed like

array[condition  && .reverse()]

or the first way is the only way to call array methods.

5 Answers

You could use Array#slice as default method.

result = fn(parm1, parm2, parm3)[condition ? 'reverse' : 'slice']();

Instead of slice and to prevent to get a copy of the array, you could implement a function which turns just this from the object without mutating it.

Array.prototype.nop = function () { return this; };

result = fn(parm1, parm2, parm3)[condition ? 'reverse' : 'nop']();
var arr = fn(parm1, parm2, parm3);
condition && arr.reverse();

Just keep it easy to read and understand:

var arr = fn(parm1, parm2, parm3);
if (condition) {
    arr.reverse();
}

Tricky solutions won't be appreciated by people who will read your code in the future.

I had an array I wanted to sort asc and desc. The sort boolean and ternary operators led me to this. Basically, if false then multiply by -1. It could probably even be simplified beyond this.

data.items
.sort((a, b) =>
    new Date(a.date) > new Date(b.date)
    ? -1 * (sort ? 1 : -1)
    : 1 * (sort ? 1 : -1)
)

What about using sort? I am not sure if browsers and node.js have the same behaviour here though:

const arr = fn(parm1, parm2, parm3).sort(()=> INVERTED ? 1 : 0);
Related