Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a slicker way of doing this?

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.

like image 546
Matt Ball Avatar asked Jul 20 '10 15:07

Matt Ball


1 Answers

How about

var x = Math.max(solveForX(), 0);
like image 69
Dave McClelland Avatar answered Oct 05 '22 21:10

Dave McClelland