Category Archives: one-liners

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));

Also posted in misc | Tagged , | 1 Comment

Unique ID

Actionscript:
  1. trace((new Date()).getTime() + Math.random()*0xFFFFFF);

A hacky way to get a unique ID, although this isn't, perfect it works well enough. For a project that you really expect to get huge amounts of traffic... you might consider using php's uniqid() function and passing it into your swf. That said, the odds of two users getting the same two ID values are about as good as the odds of you winning the lottery twice in a row.

Here is a version wrapped in a function, with a prefix argument:

Actionscript:
  1. trace(uniqid("z"));
  2.  
  3. function uniqid(prefix:String):String{
  4. return prefix + (new Date()).getTime() + Math.random()*0xFFFFFF;
  5. }

Also posted in misc, random | Tagged , | Leave a comment

new BitmapData() One-Liner

Actionscript:
  1. Bitmap(addChild(new Bitmap(new BitmapData(100,100,false,0x000000)))).bitmapData.fillRect(new Rectangle(10,10,10,10), 0xFF0000);

Also posted in BitmapData | Tagged , | Leave a comment

new Sprite() One-liner

Actionscript:
  1. var s:Sprite = Sprite(addChild(new Sprite()));

A way to make a new sprite, add it to the display list and store a reference to it.

Figured this out on my own... but have since seen it around on a few flash blogs here and there... thought it deserved a post.

Also posted in instantiation | Tagged | Leave a comment