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.
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.
Share Improve this question asked Nov 4, 2017 at 20:35 JalalJalal 3,6444 gold badges37 silver badges46 bronze badges 4- 6 The function is not called twice. Do you mean written twice? – guest271314 Commented Nov 4, 2017 at 20:38
- 1 The function will be called once. Your problem does not exist ;) – Jonas Wilms Commented Nov 4, 2017 at 20:38
- For simplicity of reading/writing store array in variable before the conditional – charlietfl Commented Nov 4, 2017 at 20:38
- Yeah sorry i meant written twice of course – Jalal Commented Nov 4, 2017 at 20:41
6 Answers
Reset to default 7You 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();
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);
The method copyWithin
performs nothing when you don't provide arguments to it (they all default to 0 by conversion from undefined
), and just like reverse
it returns the array itself (no copy is made).
So:
const result = fn(parm1, parm2, parm3)[condition ? 'reverse' : 'copyWithin']();
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.