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 in Firefox 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, a million iterations even with the "slowest" method still takes only 0.25 seconds.