Clamp Math.max(Math.min())

Actionscript:
  1. // this one-liner is good to know:
  2. // Math.max(minValue, Math.min(maxValue, valueToClamp));
  3.  
  4. // wrapped in a function it looks like this:
  5. const MIN:Number = 0;
  6. const MAX:Number = 100;
  7.  
  8. function clamp(val:Number, min:Number = MIN, max:Number = MAX){
  9.     return Math.max(min, Math.min(max, val))
  10. }
  11.  
  12. for (var i:int = 0; i<1000; i++){
  13.     var val:Number = Math.random()*1000 - 500;
  14.     // clamp the above random value between -100 and +100
  15.     trace(clamp(val, -100, 100));
  16. }

Although I show a function implementation above, I use this technique inline a good deal. If there is some value that I need to clamp I'll often just "max min it":

Actionscript:
  1. var val:Number = Math.random()*1000;
  2. // clamp it - 0-100
  3. trace(Math.max(0, Math.min(100, val));

This entry was posted in misc, one-liners and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. ookla
    Posted August 28, 2009 at 4:15 pm | Permalink

    dude, i love you, thanks!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*