Reputation: 290
is there a way to minimize this type of code plz :
position = newPosition > position ? newPosition : position;
This code is in a forEach. I'm pretty sur there's a way to achieve it but I can't remember...
Thanks all !
Upvotes: 0
Views: 56
Reputation: 3130
This is already pretty short code, but here's a more efficient version, which avoids position = position
assignment:
if (newPosition > position) position = newPosition;
As @VLAZ mentioned in a comment, a more readable version would be to use Math.max
, though this will be a bit slower as it involves a function call:
position = Math.max(position, newPosition);
In case you care about performance, I ran a quick benchmark for the case that newPosition
is not greater than position
. On Chrome on Windows at least, the if
version came out a couple of percent faster than the ?
version, while the Math.max
version came out about 20% slower than the ?
version.
Upvotes: 3