I seem to handle special cases like this somewhat frequently. There's got to be a more concise syntax or construct:
var x = solveForX(); /* some slow calculation here */
if (x < 0)
{
x = 0;
}
This is equivalent, but doesn't feel any more elegant:
var x;
x = (x = solveForX()) < 0 ? 0 : x;
Maybe there's a bit shift trick?
Update: I ran some benchmarks to compare my two favorite answers - the one I accepted, and Peter Ajtai's. Turns out Peter's is quite a bit faster! Running 1,000,000 iterations of each (I also ran a version that caches Math.max
to see how much time the lookup contributed) shows that Peter's runs in under half the time of the Math.max
version, even with max
caching.
That said, even the "slowest" method is still quite fast.
How about
var x = Math.max(solveForX(), 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With