0

I have a simple 2 line procedure that's like

if ( bgwidth < 0 ) { bgwidth = 0; }
else if ( bgwidth > 100 ) { bgwidth = 100; }

and I'm wondering what is the most compact way to do it. Is there some way with bitshift operators? :)

Subpar Web Dev
  • 3,210
  • 7
  • 21
  • 35
  • 2
    File under: Nonsensical micro-optimization // For unreadability I’d use a nested `Math.min`/`.max`, makes for a nice one-liner. (Don’t forget to not comment the code in that case, ruins the fun.) – CBroe Feb 05 '16 at 23:24

1 Answers1

3

Math.min() and Math.max() might do the trick:

Math.min(Math.max(0, bgwidth), 100);

And for readbility:

function fitBetween(value, min, max) {
  return Math.min(Math.max(min, value), max);
}
Sukima
  • 9,965
  • 3
  • 46
  • 60