0

I'm looking for a neat way to do this:

return func(arr) >= 0 ? func(arr) : arr.length;

Calling func(arr) does not modify anything, so the above works fine.

But I would still like to avoid executing func(arr) twice.

Is there a neat way to achieve that in JavaScript?

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • `func(arr) || arr.length`… – deceze Mar 04 '20 at 10:44
  • what other values does `func(arr)` return? – Nina Scholz Mar 04 '20 at 10:44
  • @deceze: That would return `true` or `false`, most certainly not `arr.length` (let alone the fact that when `func(arr)` returns -1, it will return -1 instead of `arr.length`). – goodvibration Mar 04 '20 at 10:46
  • Well, you are wrong in assuming that `||` returns a boolean. True about the `-1` though, you'd need to clarify @Nina's request there. – deceze Mar 04 '20 at 10:47
  • @deceze: Clarify that -1 < 0? I assumed that the fact that I was using `>= 0` and not `!= 0` would make that pretty obvious. – goodvibration Mar 04 '20 at 10:49
  • Fine, then something like `(i => i >= 0 ? i : arr.length)(func(arr))` is about as good as it gets. See the duplicate for further options. – deceze Mar 04 '20 at 10:51
  • @deceze: Yes, thought about it, but wasn't sure it would work. Anyway, this suggestion appears in one of the answers to one of the two questions suggested as duplicate of mine. Thanks!!! – goodvibration Mar 04 '20 at 10:54
  • Frankly though, before writing that sort of abomination, I'd do a simple `const foo = func(arr); if (foo >= 0) return foo; return arr.length;`… – deceze Mar 04 '20 at 10:58
  • If `func` always returns `-1` or an integer greater than or equal to zero, you can use this: `return ~(~func(arr)||~arr.length);`. Demo: https://jsfiddle.net/5vf3L78m/ – Unmitigated Mar 18 '20 at 20:48

1 Answers1

0

Try:

let retVal = func(arr);
return retVal  >= 0 ? retVal : arr.length;
JohnPan
  • 1,185
  • 11
  • 21